prices = ["1.6", "0.15", "1.8"]
prices.sum { |price| price.to_f }
But this returns 3.5500000000000003
, not 3.55
.
Any idea?
prices = ["1.6", "0.15", "1.8"]
prices.sum { |price| price.to_f }
But this returns 3.5500000000000003
, not 3.55
.
Any idea?
Floating-point numbers cannot precisely represent all real numbers, and floating-point operations cannot precisely represent true arithmetic operations, this leads to many surprising situations.
I advise reading: https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
You may want to use BigDecimal to avoid such problems:
require 'bigdecimal'
prices = ["1.6", "0.15", "1.8"]
prices.sum { |price| BigDecimal(price) }
#=> 3.55