Jeremy Hinegardner
12/4/2006 3:01:00 AM
On Mon, Dec 04, 2006 at 10:48:41AM +0900, 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.
You could use facets:
% sudo gem install facets
% irb
irb(main):001:0> require 'rubygems'
=> true
irb(main):002:0> require 'facet/float/round_at'
=> true
irb(main):003:0> require 'facet/float/round_to'
=> true
irb(main):004:0> x = 1.123456789
=> 1.123456789
irb(main):005:0> x.round_at(3)
=> 1.123
irb(main):006:0> x.round_at(7)
=> 1.1234568
irb(main):007:0> x.round_at(100)
=> 1.123456789
irb(main):008:0> x.round_to(0.001)
=> 1.123
irb(main):009:0> x.round_to(0.000001)
=> 1.123457
enjoy,
-jeremy
--
========================================================================
Jeremy Hinegardner jeremy@hinegardner.org