# Number format

**URL:** <https://rubytalk.org/t/number-format/33490>\
**Category:** ruby-talk\
**Created:** [5 December 2006 22:16 UTC](https://rubytalk.org/t/number-format/33490 "2006-12-05T22:16:27Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Bernard\_Kenik](https://avatars.discourse-cdn.com/v4/letter/b/ed8c4c/32.png) [@Bernard\_Kenik](https://rubytalk.org/u/Bernard_Kenik)\
**Post date:** [5 December 2006 22:16 UTC](https://rubytalk.org/t/number-format/33490/1 "2006-12-05T22:16:27Z")

</div>

You can use the number.round method, but this doesn't take a number of decimal places.

To round 1.234 to 1.23 use this code:  
x = 1.234  
x = x \* 100 # -\> 123.4  
x = x.round -\> 123  
x = x / 100.0 =\> 1.23

> **···**
>
> At least, that's the best method I can find from the Ruby docs... Dan Li Chen wrote:  
> Hi all,
> 
> I have a number, for example, 1.123456789. What is the Ruby way to  
> change it into whatever number of floating points such as 1.12,  
> 1.123,1.1234568 or 1.12345679.
> 
> Thanks,
> 
> Li
> 
> class Float  
> &nbsp;&nbsp;def places(places)  
> &nbsp;&nbsp;&nbsp;&nbsp;(self \* 10 \*\* places).truncate / 10.0 \*\* places  
> &nbsp;&nbsp;end  
> end
> 
> 1.123456789.places(5) =\> 1.12345
> 
> you can use round instead of truncate if you want to round off
> 
> alternate method  
> class Float  
> &nbsp;&nbsp;def place(places)  
> &nbsp;&nbsp;&nbsp;&nbsp;sprintf("%0.#{places}f", self).to\_f  
> &nbsp;&nbsp;end  
> end
> 
> not sure which method is most efficient

---

<div class="post-metadata">

**Author:** ![Paul\_Lutus](https://avatars.discourse-cdn.com/v4/letter/p/2bfe46/32.png) [@Paul\_Lutus](https://rubytalk.org/u/Paul_Lutus)\
**Post date:** [5 December 2006 22:30 UTC](https://rubytalk.org/t/number-format/33490/2 "2006-12-05T22:30:07Z")

</div>

Bernard Kenik wrote:

> You can use the number.round method, but this doesn't take a number of  
> decimal places.
> 
> To round 1.234 to 1.23 use this code:  
> x = 1.234  
> x = x \* 100 # -\> 123.4  
> x = x.round -\> 123  
> x = x / 100.0 =\> 1.23
> 
> At least, that's the best method I can find from the Ruby docs...

Second reply to the second copy of this identical post. This is not a good  
idea. The problem is that Ruby's numbers are stored internally in binary  
form, and this multiply -- truncate -- divide process will not work as  
intended for a lot of numbers.

It is better to retain the full resolution of binary numbers internally, and  
simply print the number with the desired number of decimal places:

> **···**
>
> --------------------------------
> 
> #!/usr/bin/ruby -w
> 
> 0.upto(10) do  
> &nbsp;&nbsp;n = rand() \* 100  
> &nbsp;&nbsp;printf("%5.02f\n",n)  
> end  
> --------------------------------
> 
> Output:
> 
> 18.64  
> 61.11  
> 58.18  
> 61.80  
> 93.98  
> 50.86  
> 55.28  
> 44.93  
> 87.23  
> 1.38  
> 11.63
> 
> --  
> Paul Lutus  
> [http://www.arachnoid.com](http://www.arachnoid.com)
