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

JavaScript floating point -- 0.1 + 0.2 !== 0.3

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

Error Messages

unexpected decimal result

Problem

Arithmetic with decimal numbers produces unexpected results. Equality comparisons with decimal results are unreliable. Causes bugs in financial calculations.

Solution

Never compare floats with ===. For money: work in cents (integers). For display: toFixed(2). For precise math: decimal.js.

Why

IEEE 754 cannot represent 0.1 exactly in binary. Representation errors accumulate.

Code Snippets

Float comparison and money handling

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

// Fix: work in cents
const price = 1050; // $10.50
const display = (price / 100).toFixed(2); // "10.50"

Revisions (0)

No revisions yet.