Rounding off floating point numbers in Ruby


If you want to round a floating point number off to two decimals, there is no standard method in Ruby that does it for you.


The general solution is

(f * 10**d).round.to_f / 10**d

where f is the floating number and d is the number of decimals.

See my code sample for adding this functionality to the Float class.

Although the above works you should concider the reason you’re performing the rounding (or equivalent) operation. If it’s for presentation reasons only a better way might be to use a format string instead, and leave the original data intact.
Here’s an example where a representation (rounded_str) of a floating point number (f) is rounded to two decimals.

rounded_str = sprintf('%.2f', f)

RSS feed | Trackback URI

Comments »

No comments yet.

Name (required)
E-mail (required - never shown publicly)
Your Comment (smaller size | larger size)
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> in your comment.