# Re: number format

**URL:** <https://www.ruby-forum.com/t/re-number-format/78458>\
**Category:** Ruby\
**Created:** [December 5, 2006, 11:16pm UTC](https://www.ruby-forum.com/t/re-number-format/78458 "2006-12-05T23:16:56Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![bbiker](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/97f17d/32.png) [@bbiker](https://www.ruby-forum.com/u/bbiker)\
**Post date:** [December 5, 2006, 11:16pm UTC](https://www.ruby-forum.com/t/re-number-format/78458/1 "2006-12-05T23:16:56Z")

</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  
def places(places)  
(self \* 10 \*\* places).truncate / 10.0 \*\* places  
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  
def place(places)  
sprintf("%0.#{places}f", self).to\_f  
end  
end

not sure which method is most efficient

---

<div class="post-metadata">

**Author:** ![bbiker](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/97f17d/32.png) [@bbiker](https://www.ruby-forum.com/u/bbiker)\
**Post date:** [December 5, 2006, 11:31pm UTC](https://www.ruby-forum.com/t/re-number-format/78458/2 "2006-12-05T23:31:01Z")

</div>

Bernard K. 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 n = rand() \* 100 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
