William
William

Reputation: 4578

How do I round to two decimal places?

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?

Upvotes: 14

Views: 20724

Answers (2)

Pravin Mishra
Pravin Mishra

Reputation: 8434

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 

Upvotes: 8

the Tin Man
the Tin Man

Reputation: 160551

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 %.

Upvotes: 16

Related Questions