如何在没有指数表示法的情况下将浮点数作为字符串?

时间:2017-09-25 22:28:33

标签: ruby string floating-point exponent

如何在不使用指数表示法的情况下将浮点数作为字符串,即以"e-10"或类似结尾的数字?我发现to_s以指数表示法返回数字。

ms = 1457000.0000000002 % 1000 # => 2.3283064365386963e-10
ms.to_s                        # => "2.3283064365386963e-10"

我想获得"0.0000000002",但我说得不对。

如果我使用上面的示例并评估"%f" % ms,我会得到"0.000000",这与"0.0000000002"大不相同。

2 个答案:

答案 0 :(得分:2)

我认为如果指定小数位数(DP)%f,它仍然有用。以你的例子为例,输出是e-10的指数,因此如果你将DP指定为10则是准确的。这是具体的:

ms = 1457000.0000000002
secs, ms = ms.divmod(1000)
my_answer = '%.10f' % ms

您的输出将为=> "0.0000000002"

答案 1 :(得分:0)

这似乎与此问题重复:

Force Ruby to not output a float in standard form / scientific notation / exponential notation

您可以使用sprintf打印格式化的数字:

ms = 1457000.0000000002
sprintf("%.10f", ms)
 => "1457000.0000000002"

重要的是要注意浮点数不是很精确 - 所以如果你告诉sprintf显示更多的数字,比如16,你就会看到这种不精确性:

sprintf("%.16f", ms)
=> "1457000.0000000002328306"

强制精度的一个技巧是使用to_r将值转换为Rational:

ms = '1457000.0000000002'.to_r
=> (7285000000000001/5000000000)
sprintf("%.16f", ms)
=> "1457000.0000000002000000"