4

是否有任何有价值的 Ruby 方法来计算浮点数中的位数?另外,我如何指定精确的何时 to_s 浮点数?

4

3 回答 3

6
# 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
于 2009-10-02T20:51:56.350 回答
2

在 Ruby 中指定浮点数的精度。您可以使用圆形方法。

number.round(2)

二是精度。

53.819.round(2) -> 53.82
于 2013-05-30T19:39:11.477 回答
1

我认为您应该查看number_with_precision助手。

number_with_precision(13, :precision => 5) # => 13.00000
于 2009-10-02T20:20:23.200 回答