【发布时间】:2009-10-02 20:10:49
【问题描述】:
是否有任何有价值的 Ruby 方法来计算浮点数中的位数?另外,如何指定精确的 to_s 浮点数?
【问题讨论】:
-
请记住,浮点十进制表示中的完整位数不一定是有用的数字。例如,0.1 不能以二进制精确表示,因此您可能不会特别高兴地发现 0.1 有 18 位不四舍五入。
标签: ruby string floating-point digits
是否有任何有价值的 Ruby 方法来计算浮点数中的位数?另外,如何指定精确的 to_s 浮点数?
【问题讨论】:
标签: ruby string floating-point digits
# Number of digits
12345.23.to_s.split("").size -1 #=> 7
# The precious part
("." + 12345.23.to_s.split(".")[1]).to_f #=> .023
# I would rather used
# 12345.23 - 12345.23.to_i
# but this gives 0.22999999999563
【讨论】:
'-'。另外,你为什么要做to_s.split("").size 而不是只做to_s.size?
在 Ruby 中指定浮点数的精度。你可以使用round方法。
number.round(2)
2 是精度。
53.819.round(2) -> 53.82
【讨论】:
"%.3f" % 53.82 => "53.820"
我认为您应该查看 number_with_precision 助手。
number_with_precision(13, :precision => 5) # => 13.00000
【讨论】: