MATLAB Answers

How do I add commas to numbers using fprintf?

158 views (last 30 days)
Bill Rooker
Bill Rooker on 8 Mar 2017
Answered: Jim Svensson on 15 Feb 2021
Hello,
How do I add commas to numbers using fprintf? My customer wants me to write out tables and have commas in the numbers to better read it. For instance, 123456789.0 would be written out as 123,456,789.0. Thanks.
Best regards,
Bill Rooker

Accepted Answer

Stephen
Stephen on 8 Mar 2017
Edited: Stephen on 8 Mar 2017
fprintf cannot do that, but you will find several FEX submissions that can create a string with commas as thousands separators:
If you read the comments to those submissions you will also find several improvements to consider.

More Answers (3)

Ted Shultz
Ted Shultz on 13 Jun 2018
you can do this in two lines. from this page : A simple way is to add this two line function:
function numOut = addComma(numIn)
jf=java.text.DecimalFormat; % comma for thousands, three decimal places
numOut= char(jf.format(numIn)); % omit "char" if you want a string out
end
Hope that helps! --ted
  4 Comments
Daven Gooden
Daven Gooden on 10 Nov 2020
@Ted Shultz: Spot on! Very clean and easy to understand/use! Thank you very mutch!

Sign in to comment.


Jim Svensson
Jim Svensson on 15 Feb 2021
I feel that in 2021 this functionality should be supported by sprintf/fprintf.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by