Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

to_d to always return 2 decimals places in ruby

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 
like image 889
ed1t Avatar asked Apr 09 '13 11:04

ed1t


People also ask

How do you round to 2 decimal places in Ruby?

Ruby has a built in function round() which allows us to both change floats to integers, and round floats to decimal places. round() with no argument will round to 0 decimals, which will return an integer type number. Using round(1) will round to one decimal, and round(2) will round to two decimals.

How do you keep a float up to 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do you set precision in Ruby?

Example: # Ensure we store z as a float by making one of the numbers a float. z = 1/3.0 # Format the float to a precision of three. format('%<num>0.3f', num: z) # => "0.333" format('%<num>0.5f', num: z) # => "0.33333" # Add some text to the formatted string format('I have $%<num>0.2f in my bank account.


2 Answers

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

like image 99
jvnill Avatar answered Oct 10 '22 17:10

jvnill


Since you are using Rails and this seems to be related to a view, there's number_with_precision:

number_with_precision(500, precision: 2) #=> "500.00"  I18n.locale = :de number_with_precision(500, precision: 2) #=> "500,00" 

For currencies I'd suggest number_to_currency:

number_to_currency(500) #=> "$500.00" 
like image 34
Stefan Avatar answered Oct 10 '22 18:10

Stefan