Surjit Nameirakpam wrote:
> Surjit Nameirakpam wrote:
>> I am getting the truncate but the round off mentioned above doesn't work
>
> Sorry.. Its the opposite round of works but truncate doesn't work
Ah, I missed that you also wanted truncate.
irb(main):001:0> class Numeric
irb(main):002:1> # same potential floating point problem as round_to
irb(main):003:1* def truncate_to( decimals=0 )
irb(main):004:2> factor = 10.0**decimals
irb(main):005:2> (self*factor).floor / factor
irb(main):006:2> end
irb(main):007:1> end
=> nil
irb(main):008:0>
irb(main):009:0* x = 12.45678
=> 12.45678
irb(main):010:0> x.truncate_to( 3 )
=> 12.456
irb(main):011:0> x.to_s.sub /(\.\d{3}).+/, '\1'
=> "12.456"
--
Posted via
http://www.ruby-forum.com/.