How to have sprintf to ignore trailing zeros

前端 未结 2 1693
终归单人心
终归单人心 2021-01-19 01:12

I want to convert a number to a string with at most 15 digits to the right of the decimal point. By at most i mean that if last digits are

相关标签:
2条回答
  • 2021-01-19 01:32

    do you mean this ?

    sprintf('%.15g', 3.0001001)
    ==> 3.0001001
    sprintf('%.15g', 3.0001)
    ==> 3.0001
    
    0 讨论(0)
  • 2021-01-19 01:39

    Simply use g instead of f:

    sprintf('%.15g', 3.0001)
    
    ans =
    
    3.0001
    

    From doc sprintf

    • %g The more compact form of %e or %f with no trailing zeros

    The above method fails for numbers lower than 0.0001 (1e-4), in which case an alternative solution is to use %f and then regexprep here it replaces one more more zeros followed by a space with a space:

    str = sprintf('%.15f ',mat);
    str = regexprep(str,'[0]+ ',' ')
    

    This method also has an issue with numbers lower than 5e-16 (such that there are only zeros for 15 digits to the right of the decimal point) having these significant digits removed.

    To solve this instead of blindly replacing zeros, we can replace a digit in the range 1-9 followed by one or more zeros and then a space with that digit followed by a space:

    str = sprintf('%.15f ',mat);
    str=regexprep(str,'([1-9])[0]+ ','$1 ')
    
    0 讨论(0)
提交回复
热议问题