Forums » Ruby on Rails » Ruby Programming Doubt

I am confused here. Just check out the below execution:

irb(main):008:0> 0.29*100
=> 29.0
irb(main):009:0> a = 0.29*100
=> 29.0
irb(main):010:0> a.to_i
=> 28
irb(main):011:0> (29.0).to_i
=> 29

What is wrong here ?

a.to_i gives 28 , while (29.0).to_i gives 29

Am i being stupid asking this.. I am not sure, but I am confused with this. Please explain.
Floats are not exact, they are approximations: IEEE 754-2008

this "error" can be called as a "Losing Money With Ruby"
because when it comes with the case of storing float in database, it will be better to
store as integer(to reduce memory) ,so to store $120.19, we would multiply the value
$120.19 by 100 to end up with 12019 cents. Any arithmetic we do, we do on the expanded
cent value and we store that in the database. If we want to display a nicely format dollar
value to the end user, we do that after we pull it back out from the database.So the
problem comes while we are storing more float money like 120.9999999999999 it will be
stored as 121. the lose is some 0.000000000001's , and for many such $ it will huge amount
of lose!!!

so if you try in irb,

=> 0.9

to get around this problem? Well from reading the ruby docs on float I'd still expect
.to_i to work, but clearly it's not actually truncating the value as documented. Instead,
you have to call round():

("0.29".to_f * 100).round