From: Phrogz Date: 2007-11-21T05:20:04+09:00 Subject: Re: How to Round off and Truncate in ruby On Nov 20, 1:07 pm, Surjit Nameirakpam wrote: > Scenario. > > I have an number x=12.45678 > > 1. I want a function to display x as a round of upto 3 decimal place as > 12.457 > 2. Similarly truncate x at 3 decimal place as 12.456 irb(main):001:0> x=12.45678 => 12.45678 irb(main):002:0> s = "%.3f" % x => "12.457" irb(main):003:0> y = (x*1000).round / 1000 => 12 irb(main):004:0> y = (x*1000).round / 1000.0 => 12.457 irb(main):007:0> class Numeric irb(main):008:1> def round_to( decimals=0 ) irb(main):010:2> factor = 10.0**decimals irb(main):011:2> (self*factor).round / factor irb(main):012:2> end irb(main):013:1> end => nil irb(main):014:0> y = x.round_to(3) => 12.457 irb(main):015:0> y = x.round_to(1) => 12.5 irb(main):016:0> y = x.round_to(-1) => 10.0 Note that 'rounding' the number is subject to floating point precision errors. Subsequent printing of a number rounded to 3 decimal places like the above may display as something like 12.4569999999999999999