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.

Frequently asked questions

How does JavaScript handle money calculation?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Floating Point Precision" snippet in JavaScript uses `// 0.1 + 0.2 !== 0.3`.
Which code does the JavaScript example use?
The "Floating Point Precision" snippet uses `// 0.1 + 0.2 !== 0.3`, from the Common Mistakes section of the JavaScript cheat sheet.
Which stacks cover "money calculation" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Floating Point Precision": All numbers in JavaScript are 64-bit floating point (IEEE 754). For financial calculations, use integer arithmetic (cents) or a decimal library.