0
prices = ["1.6", "0.15", "1.8"]
prices.sum { |price| price.to_f }

But this returns 3.5500000000000003, not 3.55.

Any idea?

Remy Wang
  • 666
  • 6
  • 26

1 Answers1

3

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
spickermann
  • 100,941
  • 9
  • 101
  • 131