Ruby Integer / Fixnum weirdness
I'm trying to write a function that pulls the lowest order number out of an integer. Eg:
> 24689.lowest_order
=> 9
Thus far I have:
class Integer
def lowest_order
Integer (self / 10.0 - self / 10) * 10
end
end
And it works....sometimes:
irb(main):002:0> n = 235
=> 235
irb(main):007:0> n.class
=> Fixnum
irb(main):004:0> n/10.0
=> 23.5
irb(main):005:0>开发者_开发百科 n/10
=> 23
irb(main):003:0> n.lowest_order
=> 5
irb(main):008:0> (n/10.0 - n/10)*10
=> 5.0
while other times it fails (no code change between examples):
irb(main):010:0> n = 232
=> 232
irb(main):021:0> n.class
=> Fixnum
irb(main):009:0> n.lowest_order
=> 1
irb(main):011:0> n/10.0
=> 23.2
irb(main):012:0> n/10
=> 23
irb(main):013:0> n/10.0 - n/10
=> 0.199999999999999
irb(main):022:0> n = Integer 232
=> 232
irb(main):023:0> n/10.0 - n/10
=> 0.199999999999999
Whats the deal? I'd rather not have to filter integer through String just to fetch the most minor part of the number.
Thanks!
Is there a reason you can't just do n % 10
or n.modulo 10
(see documentation)?
To answer the "why doesn't this work?" portion of your question, the answer is that floating point arithmetic doesn't always behave as you'd expect it to.
精彩评论