When 0.1 + 0.2 is not 0.3
Computers store decimal numbers (floats) in binary – and in binary 0.1 is a repeating fraction, like 1/3 in decimal. So it gets rounded, and sometimes that shows:
0.1 + 0.2With money that is no joke: round cents wrongly and the books will not balance at the end of the month. That is why Ruby's standard library ships BigDecimal – decimal numbers that calculate exactly the way you learned at school. You create them from strings, so the number never passes through a float:
require "bigdecimal"
BigDecimal("0.1") + BigDecimal("0.2")0.3e0 is scientific notation: 0.3 times 10 to the power of 0. to_s("F") makes it readable. And bigdecimal/util adds to_d, which turns strings and numbers into BigDecimals:
require "bigdecimal/util"
price = "19.90".to_d
quantity = 3
(price * quantity).to_s("F")BigDecimal rounds to any number of digits – by clear rules. Commercial rounding is :half_up (2.5 becomes 3); bankers round to the even number with :half_even (2.5 becomes 2), so rounding errors cancel out over many transactions:
third = BigDecimal("1") / 3
[third.round(2).to_s("F"),
BigDecimal("2.5").round(0, :half_up).to_s("F"),
BigDecimal("2.5").round(0, :half_even).to_s("F")]By the way, Ruby has a second exact kind of number built in: fractions (Rational). An r after a number makes it a fraction, and fractions compute without any rounding – a third stays a third:
puts 1/3r + 1/6r
puts 0.1r + 0.2r == 0.3r
(1/3r).to_fRule of thumb: BigDecimal for money (fixed decimal places, rounding by the rules), Rational for fractions that should never come out uneven – and good old Float for anything that is measured anyway, such as temperature or distance: it's fast and exact enough there.
gem "bigdecimal" belongs in the Gemfile). The browser has no C extensions; you are calculating with bigdecimal-pure, which rebuilds the same class in pure Ruby – out of fractions (Rational) inside. Same API, same results.total. The cell should evaluate to total – expected: 0.187e2, that is 18.70.require "bigdecimal/util"
# total = "4.20".to_d * 3 + ...