Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I round to two decimal places?

Tags:

rounding

ruby

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?

like image 677
William Avatar asked Aug 01 '13 04:08

William


People also ask

How do you round to decimal places?

There are certain rules to follow when rounding a decimal number. Put simply, if the last digit is less than 5, round the previous digit down. However, if it's 5 or more than you should round the previous digit up. So, if the number you are about to round is followed by 5, 6, 7, 8, 9 round the number up.

What is a 2 decimal place?

Rounding to Two Decimal Places is the process of rounding to hundredths place i.e. 2nd place to the right of decimal point. For Example 4.8370 rounded to two decimal places is 4.84.


1 Answers

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

like image 75
the Tin Man Avatar answered Nov 01 '22 22:11

the Tin Man