Money calculation

2 snippets across 2 stacks — JavaScript, Python

JSJavaScript

Floating Point Precision

JS · Common Mistakes
syntax
// 0.1 + 0.2 !== 0.3
example
console.log(0.1 + 0.2);         // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false

// FIX 1: Compare with tolerance
function nearlyEqual(a, b, epsilon = Number.EPSILON) {
  return Math.abs(a - b) < epsilon;
}
console.log(nearlyEqual(0.1 + 0.2, 0.3)); // true

// FIX 2: Work in integers (cents instead of dollars)
const priceInCents = 199; // $1.99
const total = priceInCents * 3; // 597 cents = $5.97

Note All numbers in JavaScript are 64-bit floating point (IEEE 754). For financial calculations, use integer arithmetic (cents) or a decimal library.

PYPython

Decimal for Precision

PY · Numbers
syntax
from decimal import Decimal
example
from decimal import Decimal

# Floating point issue
print(0.1 + 0.2)

# Decimal precision
result = Decimal("0.1") + Decimal("0.2")
print(result)
output
0.30000000000000004
0.3

Note Always pass strings to Decimal(), not floats. Decimal(0.1) inherits the float imprecision. Critical for financial calculations.