to_d to always return 2 decimals places in ruby

ed1t picture ed1t · Apr 9, 2013 · Viewed 72.9k times · Source

I'm dealing with currencies and I want to round down the number to 2 decimal places. Even if the number is 500.0, I would like it to be 500.00 to be consistent. When I do "500.00".to_d it converts it to 500.0.

Whats a good way of changing this behavior? I also use this method to round down to 2 digits and make sure it always has 2 decimals.

def self.round_down(x, n=2)
    s = x.to_s      
    l = s.index('.') ? s.index('.') + 1 + n : s.length
    s = s[0, l]
    s =  s.index('.') ? s.length - (s.index('.') + 1) == 1 ? s << '0' : s : s << '.00'      
    s.to_f
end

Answer

jvnill picture jvnill · Apr 9, 2013

In addition to mcfinnigan's answer, you can also use the following to get 2 decimal places

'%.2f' % 500 # "500.00"

This use case is known as the string format operator