简体   繁体   English

Ruby:计算浮点数中的数字

[英]Ruby: counting digits in a float number

Is there any worthy Ruby method to count the number of digits in a float? 是否有任何有价值的Ruby方法来计算浮点数的位数? Also, how do I specify the precise when to_s float numbers? 另外,如何指定to_s浮点数的精确时间?

# 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 specify precision of a float in Ruby. 在Ruby中指定float的精度。 you can use the round method. 你可以使用圆形方法。

number.round(2)

2 is the precision. 2是精度。

53.819.round(2) -> 53.82

我想你应该查看number_with_precision帮助器。

number_with_precision(13, :precision => 5) # => 13.00000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM