Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of decimal places in a Float?

I am using Ruby 1.8.7 and Rails 2.3.5.

If I have a float like 12.525, how can a get the number of digits past the decimal place? In this case I expect to get a '3' back.

like image 614
Reno Avatar asked Dec 21 '11 23:12

Reno


1 Answers

Here is a very simple approach. Keep track of how many times you have to multiple the number by 10 before it equals its equivalent integer:

def decimals(a)
    num = 0
    while(a != a.to_i)
        num += 1
        a *= 10
    end
    num   
end

decimals(1.234) # -> 3
decimals(10/3.0) # -> 16
like image 114
Matt Greer Avatar answered Oct 26 '22 09:10

Matt Greer