I have a system that's running a bunch of calculations and for some reason, everytime 0.07 shows up it appears as 0.07000000000000001
I'm well aware that floats are approximations, however I'm writing code as such:
number = '%.2f' % ( num1 - num2 )
number.to_f
Despite this, 0.07000000000000001 keeps showing up in my code and ultimately causes array sort to fail:
sort! { |a,b| b <=> a } <-- b equals 0.07000000000000001 and a equals 0.08
It raises an error saying it can't compare these two numbers. Any thoughts on how to fix this?
Update
So it appears as though the original value was 0.07351923338974675 at which point I call .round(2). I then store it in Redis temporarily and then pull it back out. When it goes to run a calculation it ends up showing up as 0.07000000000000001. It sounds like the integer comparison may be best here, unless there's an alternative solution.
num1 - num2is.round()is probably a better way to remove floating point drift.