如何四舍五入到小数点后两位?

时间:2022-06-10 08:08:35

I want any items that are rounded such as this:

我想要任何整数的项目,例如:

(5.101 * 100).round / 100.0

To be output like this:

输出如下:

5.10

Instead of this:

而不是:

5.1

How do I do this in Ruby?

我怎么用Ruby来做这个?

2 个解决方案

#1


16  

There are a couple ways, but I favor using String's % (format) operator:

有几种方法,但是我喜欢使用字符串的%(格式)运算符:

'%.2f' % [(5.101 * 100).round / 100.0] # => "5.10"

Kernel's sprintf method has the documentation for the various flags and modifiers. There's also Kernel's printf but, like I said, I'd go with %.

内核的sprintf方法有各种标志和修饰符的文档。还有内核的printf,但是,就像我说的,我选择%。

#2


9  

I hope it will help you.

我希望它能对你有所帮助。

2.0.0p195 :002 > (52.452158744).round(2)
=> 52.45 
2.0.0p195 :003 > (20.452158744).round(2)
=> 20.45 
2.0.0p195 :004 > (20.002555).round(2)
=> 20.0 
2.0.0p195 :005 > (20.012555).round(2)
=> 20.01 

#1


16  

There are a couple ways, but I favor using String's % (format) operator:

有几种方法,但是我喜欢使用字符串的%(格式)运算符:

'%.2f' % [(5.101 * 100).round / 100.0] # => "5.10"

Kernel's sprintf method has the documentation for the various flags and modifiers. There's also Kernel's printf but, like I said, I'd go with %.

内核的sprintf方法有各种标志和修饰符的文档。还有内核的printf,但是,就像我说的,我选择%。

#2


9  

I hope it will help you.

我希望它能对你有所帮助。

2.0.0p195 :002 > (52.452158744).round(2)
=> 52.45 
2.0.0p195 :003 > (20.452158744).round(2)
=> 20.45 
2.0.0p195 :004 > (20.002555).round(2)
=> 20.0 
2.0.0p195 :005 > (20.012555).round(2)
=> 20.01