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

Gotcha: JavaScript floating point arithmetic

Submitted by: @anonymous··
0
Viewed 0 times
floating pointprecision0.1 + 0.2money mathieee 754toFixed

Error Messages

0.1 + 0.2 not equal to 0.3
rounding error in calculation
money calculation wrong

Problem

JavaScript floating point math produces unexpected results like 0.1 + 0.2 !== 0.3, causing bugs in financial calculations and comparisons.

Solution

Floating point precision issues and fixes:

// The classic problem
0.1 + 0.2;           // 0.30000000000000004
0.1 + 0.2 === 0.3;   // false!

// More examples
0.3 - 0.1;           // 0.19999999999999998
1.005 * 100;          // 100.49999999999999
Math.round(1.005 * 100) / 100;  // 1 (not 1.01!)

// FIX 1: Epsilon comparison for equality
function nearlyEqual(a, b, epsilon = Number.EPSILON) {
  return Math.abs(a - b) < epsilon;
}
nearlyEqual(0.1 + 0.2, 0.3);  // true

// FIX 2: Integer math for money (cents, not dollars)
// Store as cents: $19.99 = 1999 cents
const price = 1999;  // $19.99 in cents
const tax = Math.round(price * 0.08);  // 8% tax
const total = price + tax;  // Integer math, no precision loss
const display = (total / 100).toFixed(2);  // '$21.59'

// FIX 3: Use toFixed for display (but it returns a string!)
(0.1 + 0.2).toFixed(2);  // '0.30'
parseFloat((0.1 + 0.2).toFixed(10));  // 0.3

// FIX 4: For serious financial math, use a library
// Dinero.js, currency.js, or big.js
import Dinero from 'dinero.js';
const price = Dinero({ amount: 1999, currency: 'USD' });
const tax = price.percentage(8);
const total = price.add(tax);
total.toFormat('$0,0.00');  // '$21.59'

// FIX 5: BigInt for exact large integers
9007199254740992n === 9007199254740993n;  // false (correct!)
// Regular: 9007199254740992 === 9007199254740993  // true (wrong!)

Why

All numbers in JavaScript are IEEE 754 double-precision floats. Binary floating point cannot exactly represent most decimal fractions (like 0.1), causing tiny rounding errors.

Context

JavaScript numeric calculations

Revisions (0)

No revisions yet.