4

Is there any worthy Ruby method to count the number of digits in a float? Also, how do I specify the precise when to_s float numbers?

mskfisher
  • 3,291
  • 4
  • 35
  • 48
oldhomemovie
  • 14,621
  • 13
  • 64
  • 99
  • 5
    Keep in mind that the full number of digits in a float's decimal representation is not necessarily a useful number to have. For example, 0.1 is cannot be precisely represented in binary, so you might not be particularly happy to discover that 0.1 has 18 digits without rounding. – Chuck Oct 02 '09 at 21:11

3 Answers3

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
khelll
  • 23,590
  • 15
  • 91
  • 109
  • 4
    Your solution to count digits doesn't take into account the `'-'` on negative numbers. Also, what's your reasoning for doing `to_s.split("").size` instead of just doing `to_s.size`? – Pesto Oct 03 '09 at 12:48
2

to specify precision of a float in Ruby. you can use the round method.

number.round(2)

2 is the precision.

53.819.round(2) -> 53.82
Postscripter
  • 521
  • 7
  • 18
1

I think you should check out the number_with_precision helper.

number_with_precision(13, :precision => 5) # => 13.00000
Mike Buckbee
  • 6,793
  • 2
  • 33
  • 36