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

But this returns 3.5500000000000003, not 3.55.

Any idea?

0

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

BigDecimal(nil) throws error.
Of course. Where is the nil coming from? In the array in your original question there is no nil.
["1.6", "0.15", "1.8", nil].sum(&:to_r).to_f seems to work with nil.
You can require 'bigdecimal/util' and use ["1.6", "0.15", "1.8", nil].sum(&:to_d) instead which treats nil values as 0.0, just like to_f.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.