to_d 总是在 ruby​​ 中返回 2 个小数位

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15900537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:47:32  来源:igfitidea点击:

to_d to always return 2 decimals places in ruby

ruby-on-railsrubymathdecimalcurrency

提问by ed1t

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.

我正在处理货币,我想将数字四舍五入到小数点后两位。即使数字是 500.0,我也希望它是 500.00 以保持一致。当我执行 "500.00".to_d 时,它会将其转换为 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.

什么是改变这种行为的好方法?我也使用这种方法向下舍入到 2 位数字,并确保它始终有 2 位小数。

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

回答by jvnill

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

除了 mcfinnigan 的答案,您还可以使用以下方法获得 2 位小数

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

This use case is known as the string format operator

此用例称为字符串格式运算符

回答by Stefan

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

由于您使用的是 Rails 并且这似乎与视图有关,因此有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

number_to_currency(500)
#=> "0.00"

回答by mcfinnigan

Here's a hint. 500.00 is a representation of the number 500.0

这是一个提示。500.00 是数字 500.0 的表示

Specifically, sprintf will help you:

具体来说,sprintf 将帮助您:

irb(main):004:0> sprintf "%.2f", 500.0
=> "500.00"

回答by Lars Haugseth

Do not use floating point numbers to represent money. See this questionfor a good overview of why this is a bad idea.

不要使用浮点数来表示金钱。请参阅此问题以很好地概述为什么这是一个坏主意。

Instead, store monetary values as integers (representing cents), or have a look at the moneygem that provides lots of useful functionality for dealing with such values.

相反,将货币值存储为整数(代表美分),或者查看提供许多有用功能来处理此类值的货币宝石。

回答by webaholik

There was a requirement to round DOWN.

需要四舍五入。

Most other answers round 500.016 UP to 500.02

大多数其他答案将 500.016 UP 到 500.02

Try:

尝试:

def self.round_down(x, n = 2)
  "%.#{n}f" % x.to_d.truncate(n)
end

irb(main):024:0> x=500.0; '%.2f' % x.to_d.truncate(2)
=> "500.00"
irb(main):025:0> x=500.016; '%.2f' % x.to_d.truncate(2)
=> "500.01"