Typorithm · medium

Float Precision

float-precisioninterview-questionsfloating-pointnumberepsilon
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Float Precision

0%

Tricky Output

0.1 + 0.2 is 0.30000000000000004, not 0.3, because IEEE-754 doubles cannot represent those decimals exactly — so 0.1 + 0.2 === 0.3 is false. Compare floats with Number.EPSILON and format with toFixed.

JavaScript numbers are 64-bit IEEE-754 doubles, which store values in binary. 0.1 and 0.2 have no exact binary representation, so their stored values are tiny approximations and the sum lands on 0.30000000000000004.

That is why 0.1 + 0.2 === 0.3 is false. Never compare computed floats with === when fractional arithmetic is involved.

Instead, test whether the difference is below a tolerance — Math.abs(a - b) < Number.EPSILON — and use toFixed (which returns a string) only for display, not for further math.

01

0.1 + 0.2 === 0.30000000000000004, not 0.3.

02

Compare floats with Math.abs(a - b) < Number.EPSILON.

03

toFixed formats for display and returns a string.

0.1 + 0.2            // 0.30000000000000004
0.1 + 0.2 === 0.3    // false
Math.abs((0.1 + 0.2) - 0.3) < Number.EPSILON // true
(0.1 + 0.2).toFixed(2) // "0.30"

Read the implementation

Connect each part of the code to the concept before you type.

1. Not exactly 0.3

IEEE-754 doubles cannot store 0.1 or 0.2 exactly, so their sum drifts to 0.30000000000000004.

0.1 + 0.2            // 0.30000000000000004

2. === fails

Because the sum is not exactly 0.3, strict equality against 0.3 is false.

0.1 + 0.2 === 0.3    // false

3. Compare with EPSILON

Comparing the absolute difference against Number.EPSILON treats values within rounding error as equal.

Math.abs((0.1 + 0.2) - 0.3) < Number.EPSILON // true

4. Format for display

toFixed(2) rounds to a fixed number of decimals and returns a string for display.

(0.1 + 0.2).toFixed(2) // "0.30"

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Float Precision: Lesson & Practice · Typorithm | ApplyDjinn