红宝石四舍五入到小数点后两位并保持零

问题描述:

我想在 ruby​​ 中将数字四舍五入到小数点后两位,这样

i want to round off a number upto two decimal place in ruby such that

(0.02 * 270187).round(2) 是 5403.74 这是正确的

(0.02 * 270187).round(2) is 5403.74 which is correct

但是

(0.02 * 278290).round(2) 是 5565.8 与之前的不一致

(0.02 * 278290).round(2) is 5565.8 which is not consistent with previous one

我想让它看起来像 5565.80

i want to make it look like 5565.80

请告诉我如何在 ruby​​ 中做到这一点

Please tell me how can i do it in ruby

这样做可以解决问题:

> sprintf("%.2f",(0.02 * 270187))
#=> "5403.74" 
> sprintf("%.2f",(0.02 * 278290))
#=> "5565.80"
> sprintf("%.2f",(0.02 * 270187)).to_f > 100  # If you plan to Compare something with result
#=> true 

> '%.2f' % (0.02 * 270187)
#=> "5403.74"
> '%.2f' % (0.02 * 278290)
#=> "5565.80" 

演示

注意:结果始终是一个字符串,但由于您在进行四舍五入,因此我假设您无论如何都是出于演示目的而这样做的.sprintf 可以几乎以您喜欢的任何方式格式化任何数字.如果您打算将任何内容与此结果进行比较,请通过在末尾添加 .to_f 将此字符串转换为浮点数.像这样

Demo

Note: The result is always a string, but since you're rounding I assume you're doing it for presentation purposes anyway. sprintf can format any number almost any way you like. If you are planning to compare anything with this result then convert this string to float by adding .to_f at the end. Like this