liveBook · Manning

Number rounding

As explained in JavaScript in Depth

The process of approximating a numeric value to a nearby representable value.

Why does `0.1 + 0.2` produce `0.30000000000000004`? Both decimal fractions repeat in binary, so storing each in a 52-bit significand first requires rounding. Addition aligns their exponents, then normalizes and rounds the result again. The discrepancy is a consequence of binary floating-point representation, not a JavaScript-specific bug. section 3.1.1

Table 3.3 Representing 0.1 and 0.2 as floating-point numbers
Value
Sign
Exponent
Significand
0.1
0
01111111011
1.1001100110011001100110011001100110011001100110011010
0.2
0
01111111100
1.1001100110011001100110011001100110011001100110011010

Compare the exponents and repeating significand patterns stored for 0.1 and 0.2. section 3.1.1

Rounding also appears explicitly in `Math.round(n)` (nearest integer), `Math.floor(n)` (down), and `Math.ceil(n)` (up). These operations differ from the rounding needed to fit a result into a floating-point significand. For approximate comparisons, `Number.EPSILON` provides a reference near 1; a comparison can scale it by the magnitudes being compared. section 3.1.1

How JavaScript in Depth covers it

How deep it goes
Works through exponent alignment, binary addition, normalization, and fitting the result into 52 significand bits.
Examples
Uses `0.1 + 0.2`, stored binary patterns, `Number.EPSILON`, and `Math.round`, `Math.floor`, and `Math.ceil`.
What it assumes
Builds from binary arithmetic and a scientific-notation analogy rather than requiring prior floating-point internals.
What you can do after
Diagnose/debug with it when decimal-looking arithmetic yields a nearby, unexpected value.
How it connects
Connects rounding to binary fractions, IEEE 754 floating-point, significands, exponents, and approximate equality.

Also explained in

Compare how 7 books explain number rounding →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of JavaScript in Depth. The section links point to the parts of the book it draws on.