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
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.
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 %.
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.
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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With