How to print an integer with a thousands separator in Matlab?

后端 未结 2 1140
轮回少年
轮回少年 2021-02-20 00:08

I would like to turn a number into a string using a comma as a thousands separator. Something like:

x = 120501231.21;
str = sprintf(\'%0.0f\', x);
2条回答
  •  无人共我
    2021-02-20 00:26

    Here's the solution using regular expressions:

    %# 1. create your formated string 
    x = 12345678;
    str = sprintf('%.4f',x)
    
    str =
    12345678.0000
    
    %# 2. use regexprep to add commas
    %#    flip the string to start counting from the back
    %#    and make use of the fact that Matlab regexp don't overlap
    %#    The three parts of the regex are
    %#    (\d+\.)? - looks for any number of digits followed by a dot
    %#               before starting the match (or nothing at all)
    %#    (\d{3})  - a packet of three digits that we want to match
    %#    (?=\S+)   - requires that theres at least one non-whitespace character
    %#               after the match to avoid results like ",123.00"
    
    str = fliplr(regexprep(fliplr(str), '(\d+\.)?(\d{3})(?=\S+)', '$1$2,'))
    
    str =
    12,345,678.0000
    

提交回复
热议问题