Reputation: 17
I stored a decimal value 0.57 as number (10,2) in the database. When I retrieve the value on my screen using Ruby on Rails it shows 0.570000000001
Upvotes: 0
Views: 1169
Reputation: 54223
Instead of saving value
as number (10,2)
, you could save 100 * value
as an integer.
In other words, work with cents instead of dollars. This lets you avoid floating point errors.
Upvotes: 1
Reputation: 931
You can use the BigDecimal class, and store it as Decimal or String in database
for example
sum = BigDecimal("0")
10_000.times { sum += BigDecimal("0.0001") }
sum.to_f # => 1.0
another_sum = 0
10_000.times { another_sum += 0.0001 }
another_sum # => 0.9999999999999062
Upvotes: 0