如何让sprintf忽略尾随零 [英] How to have sprintf to ignore trailing zeros
问题描述
我想将数字转换为小数点右边最多 15个数字的字符串.最多 的意思是,如果最后一位全为零,则打印这些位是无用的.
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 all zeros it is useless to print them.
例如:
sprintf('%.15f', 3.0001)
==> '3.000100000000000'
到目前为止,一切都很好,但是由于所有的尾随数字都为零,我更希望:
So far so good, but here as all trailing digits are all zeros, I would have prefered:
==> '3.0001'
是否有使用sprintf
格式说明符的简单方法,还是应该手动对输出进行后处理以删除尾随的零?
Is there a simple way to do it with sprintf
format specifiers or should I manually post-process output to remove trailing zeros ?
注意:我正在与matlab合作,以防sprintf
有其他替代方法.
NB: I'm working with matlab in case there would be any other aternative to sprintf
.
推荐答案
只需使用g
而不是f
:
sprintf('%.15g', 3.0001)
ans =
3.0001
来自doc sprintf
- %g%e或%f的更紧凑形式,没有结尾的零
对于小于0.0001(1e-4)的数字,上述方法将失败,在这种情况下,另一种解决方案是使用%f,然后regexprep
在这里,它用一个空格替换一个更多的零:
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]+ ',' ')
此方法还存在一个问题,即删除了这些有效数字后,数字小于5e-16(小数点右边的15位数字只有零).
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.
要解决此问题,而不是盲目地替换零,我们可以替换范围为1-9的数字,后跟一个或多个零,然后替换为该数字后跟空格的空格:
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 ')
这篇关于如何让sprintf忽略尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!