How do I round up to two decimal places?

advertisements

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?


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