what’s easiest way to compare a Float & BigDecimal (i.e. like a equals
mechanism)? It seems that “==” does NOT work as they are different
types. Is there a way to do a comparison without having to convert
types?
It works fine for me. If I do something like this:
f = 0.1
b = BigDecimal.new(‘0.1’)
puts ‘yes’ if f == b
It will return true. I’ve always stayed clear of the equality operator
with floating point numbers. Floating point cannot represent all
numbers exactly, so comparing it with something like a BigDecimal (which
can represent all numbers exactly) might be problematic.
You can rely on comparing floating point numbers for less than or
greater than only.
You can not reliably compare floating point numbers for equality period.
what’s easiest way to compare a Float & BigDecimal (i.e. like a equals
mechanism)? It seems that “==” does NOT work as they are different
types. Is there a way to do a comparison without having to convert
types?
Actually, there is none. Why don’t you just let Ruby do the job and
multiply the bigdecimal with 1.0 when comparing? Also, as previously
noted, == operator with floats is not … reliable.
types?
Actually, there is none. Why don’t you just let Ruby do the job and
multiply the bigdecimal with 1.0 when comparing? Also, as previously
noted, == operator with floats is not … reliable.
br,
pen
BigDecimal objects should have a to_f method. Using that would probably
be more clear than multiplying by 1.0 (a seamingly meaningless thing to
do).
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.