More JavaScript answers

by Danny
Published 2 min read

JavaScript numbers are binary floating point, so values like 0.1 cannot be stored exactly. Learn why, and how to compare, round and handle money safely.

The short answer

#

JavaScript stores numbers as 64-bit binary floating point, and decimals such as 0.1 and 0.2 cannot be represented exactly in binary. The tiny errors add up, so the result is 0.30000000000000004. Compare with a tolerance, round for display, and use whole numbers (such as pence) for money.


_10
0.1 + 0.2; // 0.30000000000000004
_10
_10
const closeEnough = Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON;
_10
console.log(closeEnough); // true

Why it happens

#

Every JavaScript number is an IEEE 754 double-precision value. It is not a JavaScript quirk: Python, Java, C and most other languages give the same answer for the same calculation with doubles.

In base 10, one third is 0.3333... forever, so you have to cut it off somewhere. In base 2 the same thing happens to one tenth. 0.1 in binary is a repeating pattern, so the computer stores the nearest value it can fit in 52 bits of fraction, which is very slightly more than 0.1. The same goes for 0.2. When you add the two approximations, the result lands on a different double from the one nearest to 0.3.


_10
(0.1).toPrecision(21); // '0.100000000000000005551'
_10
(0.3).toPrecision(21); // '0.299999999999999988898'

Integers are exact up to Number.MAX_SAFE_INTEGER (9,007,199,254,740,991). The problem only shows up with fractions, or with integers beyond that limit.

How to fix it

#

Work in whole units for money

Store prices as integers in the smallest unit, such as pence or cents, and only divide when you display them. Integer addition and multiplication are exact within the safe range.


_10
const prices = [1999, 450, 10]; // pence
_10
const total = prices.reduce((sum, p) => sum + p, 0); // 2459
_10
_10
const formatted = new Intl.NumberFormat('en-GB', {
_10
style: 'currency',
_10
currency: 'GBP',
_10
}).format(total / 100); // '£24.59'

For very large amounts, BigInt gives exact integers of any size.

Round when you display

If you only need a tidy number on screen, round at the last moment and keep the full value for further calculations.


_10
const result = 0.1 + 0.2;
_10
_10
result.toFixed(2); // '0.30' (a string)
_10
Number(result.toFixed(2)); // 0.3
_10
Math.round(result * 100) / 100; // 0.3

Compare with a tolerance

Never test fractional results with ===. Check whether they are close enough instead. Number.EPSILON is the gap between 1 and the next double, which suits values around 1. For larger values, scale the tolerance.


_10
function nearlyEqual(a, b, tolerance = 1e-9) {
_10
return Math.abs(a - b) <= tolerance * Math.max(1, Math.abs(a), Math.abs(b));
_10
}
_10
_10
nearlyEqual(0.1 + 0.2, 0.3); // true
_10
nearlyEqual(1000.1 + 1000.2, 2000.3); // true

Use a decimal library when you need exact decimal maths

For finance, tax or scientific work with many decimal steps, use a well-maintained arbitrary-precision library such as decimal.js or big.js. They store numbers in base 10, so 0.1 + 0.2 really is 0.3.


_10
import Decimal from 'decimal.js';
_10
_10
new Decimal('0.1').plus('0.2').toString(); // '0.3'

Pass strings to the constructor, not numbers, or the binary error is already baked in before the library sees it.

Common pitfalls

#
  • Rounding too early. Rounding after every step can drift further than the original error. Keep full precision and round once at the end.
  • Trusting toFixed for exact rounding. (1.005).toFixed(2) gives '1.00', because 1.005 is really stored as slightly less. Work in integers if the rounding must be exact.
  • Using Number.EPSILON for big values. The gap between doubles grows with size, so Number.EPSILON is far too small a tolerance for numbers in the thousands.
  • Large IDs from APIs. A 64-bit ID such as 9007199254740993 silently changes when parsed as a number. Keep IDs as strings.
  • Assuming loops land exactly. A loop that adds 0.1 until it reaches 1 may never equal 1. Count with integers and divide.
#

Was this resource helpful?