Ruby: floating point digit counting

Is there any worthy Ruby method for counting the number of digits in a float? Also, how can I specify the exact value of to_s floating point numbers?

+4
source share
3 answers
# 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 
+6
source

to indicate float accuracy in Ruby. You can use the round method.

 number.round(2) 

2 - accuracy.

 53.819.round(2) -> 53.82 
+1
source

I think you should check the number_with_precision helper.

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

All Articles