It's been quite a while since I last used D Programming Language, and now I'm using it for some project that involves scientific calculations.
自从我上次使用D编程语言以来已经有一段时间了,现在我将它用于一些涉及科学计算的项目。
I have a bunch of floating point data, but when I print them using writefln
, I get results like: 4.62593E-172
which is a zero! How do I use string formatting % stuff to print such things as 0?
我有一堆浮点数据,但是当我使用writefln打印它们时,我得到的结果如下:4.62593E-172这是一个零!如何使用字符串格式化%stuff来打印0这样的东西?
Right now I'm using a hack:
现在我正在使用黑客:
if( abs(a) < 0.0000001 )
writefln(0);
else
writefln(a);
it does the job, but I want to do it using the formatting operations, if possible.
它完成了这项工作,但我希望使用格式化操作,如果可能的话。
UPDATE
someone suggested writefln("%.3f", a)
but the problem with it is that it prints needless extra zeros, i.e. 0
becomes 0.000
and 1.2
becomes 1.200
Can I make it also remove the trailing zeros?
有人建议使用writefln(“%。3f”,a),但问题是它打印了不必要的额外零,即0变为0.000而1.2变为1.200我可以使它也删除尾随零吗?
4 个解决方案
#1
5
Short answer: This can't be done with printf format specifiers.
简短回答:使用printf格式说明符无法做到这一点。
Since D uses the same formatting as C99's vsprintf()
, you find your answer in this thread: Avoid trailing zeroes in printf()
由于D使用与C99的vsprintf()相同的格式,因此您可以在此主题中找到答案:避免在printf()中使用尾随零
#2
2
Try something like
尝试类似的东西
writefln("%.3f", a);
#3
1
Federico's answer should work, for more information check the format specifiers section.
Federico的答案应该有效,有关更多信息,请查看格式说明符部分。
#4
-1
I see you are currently using Phobos, however what you are trying to do is supported in Tango.
我发现你现在正在使用Phobos,但是Tango支持你想要做的事情。
Stdout.formatln("{:f2}", 1.2);
will print "1.20"
将打印“1.20”
#1
5
Short answer: This can't be done with printf format specifiers.
简短回答:使用printf格式说明符无法做到这一点。
Since D uses the same formatting as C99's vsprintf()
, you find your answer in this thread: Avoid trailing zeroes in printf()
由于D使用与C99的vsprintf()相同的格式,因此您可以在此主题中找到答案:避免在printf()中使用尾随零
#2
2
Try something like
尝试类似的东西
writefln("%.3f", a);
#3
1
Federico's answer should work, for more information check the format specifiers section.
Federico的答案应该有效,有关更多信息,请查看格式说明符部分。
#4
-1
I see you are currently using Phobos, however what you are trying to do is supported in Tango.
我发现你现在正在使用Phobos,但是Tango支持你想要做的事情。
Stdout.formatln("{:f2}", 1.2);
will print "1.20"
将打印“1.20”