File Exchange

image thumbnail

num2sepstr

version 1.41.0.0 (76.2 KB) by Robert
num2str with thousands separators

5 Downloads

Updated 25 Aug 2017

View Version History

GitHub view license on GitHub

Calls num2str on the input number (with the optionally specified format) and adds commas as thousands separators.

Cite As

Robert (2020). num2sepstr (https://github.com/raaperrotta/num2sepstr), GitHub. Retrieved .

Comments and Ratings (7)

Andrzej Marciniak

One line solution of Andreas J. is great. THX

Zacharias

Yona

Robert

Thanks for your suggestion, Stephen!

It turns out the biggest difference in execution time comes from the switch from num2str to sprintf. I have changed my implementation to use sprintf.

I also now use regexprep instead of my previous comma insertion method. Thanks to you both for that insight.

Stephen Cobeldick

Faster than both this FEX submission and also Andreas J's code:

str = sprintf(fmt,val);
C = regexpi(str,'^(\D*\d{0,3})(\d{3})*(\D\d*)?$','once','tokens');
if numel(C)
str = [C{1},regexprep(C{2},'(\d{3})',',$1'),C{3}];
end

Robert

Hi Andreas, thanks for the comment! I love a good one-line solution. However, I find that this does not handle numbers after the decimal the way I would expect and it isn't quite as fast as num2sepstr (in my very simple tests).

sep = ',';
strI = num2str(pi*1e7);
strO = regexprep(strI,'[0-9](?=(?:[0-9]{3})+(?![0-9]))',['$&',sep])

strO =
31,415,926.5,359

Andreas J.

interesting solution, i did it with this line:

strO = regexprep(strI,'[0-9](?=(?:[0-9]{3})+(?![0-9]))',['$&',sep]);

MATLAB Release Compatibility
Created with R2016a
Compatible with any release
Platform Compatibility
Windows macOS Linux
Acknowledgements

Inspired: parseTime, statusbarTimer

Community Treasure Hunt

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

Start Hunting!