5.3. Rounding Floating Point Values

Kirk: What would you say the odds are on our getting out of here?

Spock: It is difficult to be precise, Captain. I should say approximately 7824.7 to one.

—Star Trek, “Errand of Mercy

If you want to round a floating point value to an integer, the method round will do the trick:

pi = 3.14159
new_pi = pi.round   # 3
temp = -47.6
temp2 = temp.round  # -48

Sometimes we want to round not to an integer but to a specific number of decimal places. In this case, we could use sprintf (which knows how to round) and eval to do this:

pi = 3.1415926535
pi6 = eval(sprintf("%8.6f",pi))  # 3.141593
pi5 = eval(sprintf("%8.5f",pi))  # 3.14159
pi4 = eval(sprintf("%8.4f",pi))  # 3.1416

Of course, this is somewhat ugly. Let’s encapsulate ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.