# Re: How do I round off a float to x decimal places

**URL:** <https://www.ruby-forum.com/t/re-how-do-i-round-off-a-float-to-x-decimal-places/72024>\
**Category:** Ruby\
**Created:** [October 13, 2006, 5:49pm UTC](https://www.ruby-forum.com/t/re-how-do-i-round-off-a-float-to-x-decimal-places/72024 "2006-10-13T17:49:36Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![phrogz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/2acd7d/32.png) [@phrogz](https://www.ruby-forum.com/u/phrogz)\
**Post date:** [October 13, 2006, 5:49pm UTC](https://www.ruby-forum.com/t/re-how-do-i-round-off-a-float-to-x-decimal-places/72024/1 "2006-10-13T17:49:36Z")

</div>

From: Jatinder S. [[mailto:removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)]

> This might be a very naive question but I looked through ruby:Float  
> documentation for a method which round off’s a float number  
> to x decimal  
> places with no luck.

To get the result as a number (which, due to floating point precision,  
might not be an exact representation of what you wanted):  
class Numeric  
def round\_to( decimals )  
factor = 10 \*\* decimals  
( self \* factor ).round \* 1.0 / factor  
end  
end

(Bonus - works with “negative” decimals, to round to tens or hundreds or  
thousands.)

To get the result as a string, which is probably what you really wanted:  
class Numeric  
def round\_to\_string( decimals )  
“%.#{decimals}f” % self  
end  
end
