可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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
回答1:
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
回答2:
Here's a hint. 500.00 is a representation of the number 500.0
Specifically, sprintf will help you:
irb(main):004:0> sprintf "%.2f", 500.0 => "500.00"
回答3:
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"
回答4:
Do not use floating point numbers to represent money. See this question for a good overview of why this is a bad idea.
Instead, store monetary values as integers (representing cents), or have a look at the money gem that provides lots of useful functionality for dealing with such values.