Truncating Floats

Hi,

I need to truncate some Floats and found this:
http://www.approximity.com/cgi-bin/blogtariAgile/index.rb/+Forth/RetroWeb.rdoc

It suggests:
  class Float
    def truncate(sd=2)
      scale=(10**sd).to_f
      (self * scale).to_i / scale
    end
  end
  a=0.255
  a.truncate(2) #-> 0.25

Is there a better way to do the above? I'm sort of surprised that there
isn't a builtin, but perhaps I'm not looking in the right place.

Thanks,
Keith

Probably cause you can do it in one line:

('%.2f' % 0.255).to_f

Probably cause you can do it in one line:

('%.2f' % 0.255).to_f

That's rounding, not truncating.

For some purposes, there's BigDecimal, where x.yz is really two decimals
(and not an approximation as a flost takes)

And behold! BigDecimal#floor takes an argument, the number of digits you
want (had to look that up myself; learn something new every day :slight_smile:

+--- Kero ------------------------- kero@chello@nl ---+

all the meaningless and empty words I spoke |
                      Promises -- The Cranberries |

+--- M38c --- http://members.chello.nl/k.vangelder ---+

Okay, how about:

0.255.to_s.sub(/(\.\d{2})\d+/, "\\1").to_f

James Edward Gray II

···

On Oct 1, 2005, at 4:31 AM, Kero wrote:

Probably cause you can do it in one line:

('%.2f' % 0.255).to_f

That's rounding, not truncating.

for more enjoyment and greater efficiency:
(s=2.33333.to_s + "00").slice(0,s.index(".")+3)

"James Edward Gray II" <james@grayproductions.net> wrote in message
news:AF6D1EBB-D94C-40C7-913E-CE6137D99FFA@grayproductions.net...

···

On Oct 1, 2005, at 4:31 AM, Kero wrote:

Probably cause you can do it in one line:

('%.2f' % 0.255).to_f

That's rounding, not truncating.

Okay, how about:

0.255.to_s.sub(/(\.\d{2})\d+/, "\\1").to_f

James Edward Gray II