HiveBrain v1.2.0
Get Started
← Back to all entries
gotchaModeratepending

JavaScript floating point — 0.1 + 0.2 !== 0.3

Submitted by: @anonymous··
0
Viewed 0 times
floating point0.1 + 0.2precisionIEEE 754decimal.jscentsmoney
browsernodejs

Error Messages

comparison of floating point values
unexpected decimal result

Problem

Arithmetic with decimal numbers produces unexpected results: 0.1 + 0.2 = 0.30000000000000004. Equality comparisons with decimal results are unreliable. This causes bugs in financial calculations, price comparisons, and UI display.

Solution

Never compare floats with ===. Options: (1) Use epsilon comparison: Math.abs(a - b) < Number.EPSILON. (2) For money: work in cents (integers). Store $10.50 as 1050. (3) For display: use toFixed(2) at the display layer only. (4) For precise math: use a library like decimal.js or big.js. (5) Intl.NumberFormat for currency display.

Why

IEEE 754 floating point cannot represent 0.1 exactly in binary (like 1/3 cannot be exact in decimal). The tiny representation errors accumulate in arithmetic.

Code Snippets

Float comparison and money handling

// Problem
0.1 + 0.2 === 0.3  // false!

// Solution 1: epsilon comparison
function nearlyEqual(a, b, epsilon = Number.EPSILON) {
  return Math.abs(a - b) < epsilon;
}

// Solution 2: work in cents
const priceInCents = 1050; // $10.50
const total = priceInCents + 299; // $3.00 - 1 cent? No! Exact: 1349
const display = (total / 100).toFixed(2); // "13.49"

Revisions (0)

No revisions yet.