Programming11 min read

Why 0.1 + 0.2 breaks unit conversion in JavaScript

JavaScript doubles round at every step. Convert through one canonical unit, test with ULP or relative tolerance, and round only when you display.

The number 0.30000000000000004 with its last digit in orange, beside a ring of flow units around a central m³/s node and the 64 bits of 0.1

You type 0.000021 m³/s into a converter, switch the unit to litres per second and expect to see 0.021. JavaScript gives you 0.020999999999999998 instead. A test written with toBe goes red. Worse, a form validator whose limit was built from a converted value now rejects a number the user typed correctly.

So what went wrong here? Is the conversion factor wrong, or the arithmetic? And if every multiplication can be off by a hair, can you still trust a value that went through five conversions, or does it slowly wander away from where it started?

The short answer is that JavaScript numbers are binary IEEE 754 doubles. Most decimal fractions cannot be stored exactly, and every arithmetic step rounds. More rounding does not cure that. What does is one canonical unit, conversion only at the edges, comparisons in ULP or relative tolerance, and rounding only when you print.

This guide shows how we do that in civilDesk, our offline toolkit for civil engineers. The code and tests come from its repository, and every number below was measured with Node 26.10.0 on 2026-12-01.

Why 0.1 + 0.2 is not 0.3 in JavaScript

Every JavaScript number is a 64 bit binary floating point value as defined by IEEE 754, which the ECMAScript spec calls the Number type. It has 1 sign bit, 11 exponent bits and 52 stored fraction bits, which gives 53 significant binary digits. A fraction like 1/10 has an infinite expansion in base 2, the same way 1/3 has one in base 10, so it gets cut off and rounded to the nearest representable value.

That nearest value for 0.1 is 0.1000000000000000055511151... (its bit pattern is 0x3FB999999999999A, and the final A is where the infinite ...999 was rounded up). 0.2 is off in the same direction. Add them, round the result to 53 bits again, and you land on the double just above 0.3.

js
0.1 + 0.2;                 // 0.300000000000000040.1 + 0.2 === 0.3;         // false0.1 + 0.2 - 0.3;           // 5.551115123125783e-17[...Array(10)].reduce((s) => s + 0.1, 0); // 0.9999999999999999

The difference is not noise. It is exactly one step between neighbouring doubles at that magnitude, 2^-54. That step has a name, one ULP, short for a unit in the last place.

Five neighbouring doubles around 0.3 on a number line, where 0.3 and the result of 0.1 + 0.2 sit next to each other, one ULP of 2^-54 apart
The double nearest to 0.3 and the result of 0.1 + 0.2 are neighbours, one ULP apart

The size of one ULP grows with the number. Number.EPSILON is the ULP at 1.0. At 50 the gap to the next double is 32 times larger, and at 854.698 it is 512 times larger.

Number.EPSILON, one ULP at 1
2.220446049250313e-16
one ULP at 50
7.105427357601002e-15
one ULP at 854.698
1.1368683772161603e-13

So the relative precision is roughly constant at about 16 significant decimal digits, while the absolute precision depends entirely on the magnitude. Keep that in mind, because it decides how you should compare numbers later on. For the full theory, David Goldberg's What Every Computer Scientist Should Know About Floating-Point Arithmetic is still the reference.

Where the error hides in a unit conversion

An engineering app converts all the time, from litres per second to cubic metres per second, feet to metres, psi to pascals. Each conversion is one or two multiplications or divisions, and each one rounds. Usually the result is the double nearest to the true answer, sometimes it is the next one over.

The first trap is the constant itself. 1000 is exact in binary, but 0.001 is not. So x / 1000 is one correctly rounded operation on exact inputs, while x * 0.001 first uses an already rounded constant and then rounds again. We counted it for the integers 1 to 10 000, and k * 0.001 and k / 1000 give different doubles for 1338 of them.

js
9 * 0.001;    // 0.0090000000000000019 / 1000;     // 0.00913 * 0.001;   // 0.01300000000000000113 / 1000;    // 0.013

The second trap is the round trip. Convert to the base unit and back, and you expect the original value. Over the same 10 000 integers, k * 0.001 * 1000 failed to return k exactly 1307 times (the first is 9, which comes back as 9.000000000000002), and k / 1000 * 1000 failed 175 times. In both cases the miss was at most one ULP. Neither form is exact, but one is clearly better.

The third trap is computing a constant instead of writing it down. A cubic foot is exactly 0.028316846592 m³ (0.3048³, since the foot is defined as exactly 0.3048 m). Write 0.3048 ** 3 in code and you get 0.028316846592000004. A US gallon is exactly 231 in³, but 231 * 0.0254 ** 3 gives 0.0037854117839999997. Type the exact decimal literal from the definition and let the parser round it once.

How civilDesk converts flow through one canonical unit

civilDesk has seven hydraulic calculators that take a flow (pipe sizing, Manning channel, Hazen-Williams, Darcy-Weisbach, rational method, weir and orifice, culvert). Each one used to carry its own inline unit === 'l/s' ? v * 1000 : v. When we extracted that idiom into src/app/shared/utils/flow-units.util.ts, we wrote the contract into the file.

ts
/** * Contract: *   - The canonical internal unit is ALWAYS m³/s. Nothing stores l/s. *   - Conversion happens exactly once, at the I/O boundary. *   - Round-tripping any value through any unit pair returns the original *     to within 1 ulp. This is why `fromM3s` multiplies and `toM3s` divides by *     the same integer factor, rather than multiplying by its reciprocal: *     `x / 1000` is correctly rounded, `x * 0.001` is not. */export const LITRES_PER_CUBIC_METRE = 1000;export function flowToM3s(value: number, unit: FlowUnit): number {  if (!Number.isFinite(value)) return value;  return unit === 'l/s' ? value / LITRES_PER_CUBIC_METRE : value;}export function flowFromM3s(m3s: number, unit: FlowUnit): number {  if (!Number.isFinite(m3s)) return m3s;  return unit === 'l/s' ? m3s * LITRES_PER_CUBIC_METRE : m3s;}

Three decisions sit in those few lines. The model only ever holds m³/s, so a value is converted at most twice in its life, once when the user types it and once when it is shown. Both directions use the same exact integer, one dividing and one multiplying. And a non-finite input (NaN, Infinity) is passed through untouched, because a helper that turns a bad value into a plausible zero hides the bug instead of showing it.

The display side is an Angular pipe, so templates never convert by hand. They write {{ value_in_m3s | flow: flowUnit | smartNumber }}, where the flow pipe calls flowFromM3s and the smartNumber pipe formats. More on that one below.

Presets are written in pairs, not derived

Default values and validator limits are the place where a one ULP error becomes a user-visible bug. If you write Validators.max(flowFromM3s(0.05, unit)) and the conversion lands one ULP low, the limit becomes something like 49.999999999999996 and the user's "50" is rejected. For 0.05 m³/s the conversion happens to be exact (0.05 * 1000 is 50), but that is luck about where those values fall in binary. Small flows are less lucky.

js
0.000021 * 1000;  // 0.0209999999999999980.000035 * 1000;  // 0.034999999999999996

We checked how common that is. Of the 1000 flows from 0.000001 to 0.001 m³/s in steps of 0.000001, 256 do not convert to the round L/s value you would type. So civilDesk authors presets as explicit pairs and picks one.

ts
export function flowPreset(presets: { m3s: number; lps: number }, unit: FlowUnit): number {  return unit === 'l/s' ? presets.lps : presets.m3s;}// flowPreset({ m3s: 0.05, lps: 50 }, unit)

A default and a validator bound are numbers a person decided on, not numbers the program computed. Writing both values down makes that class of bug impossible instead of unlikely.

Do chained conversions drift? We measured it

The general unit converter in civilDesk works differently from the flow helper. Every unit has a factor to the SI base unit in unit-definitions.ts, and a conversion goes through the base.

ts
// unit-definitions.ts (flow excerpt): factor = multiplier to the SI base unit{ key: 'ls',     symbol: 'L/s',     factor: 0.001 },{ key: 'ft3s',   symbol: 'ft³/s',   factor: 0.028316846592 },{ key: 'galmin', symbol: 'gal/min', factor: 0.003785411784 / 60 },// unit-converter.component.tsconst si = v * from.factor;   // toBaseconst out = si / to.factor;   // fromBase

The usual fear is that each hop adds error and a value that goes through many conversions slowly wanders off. We tested it directly. We took 10 000 flows between 0 and 1000 L/s with three decimals generated deterministically with the same LCG seed civilDesk's tests use, and sent each one around a ring of L/s, gal/min, ft³/s, m³/h, L/min and back to L/s. One lap is five conversions. We ran three ways of writing a single conversion with the same factors.

StrategyExact after 1 lapWithin 1 ULP after 10 lapsWorst case after 1000 laps
v * fa / fb (civilDesk)74.2 %97.5 %4 ULP
v * fa * (1 / fb)33.4 %51.7 %19 ULP
v * (fa / fb), pair factor26.1 %38.7 %49 ULP
Values back exactly after 1 lap (%)
  • v * fa / fb74.2
  • v * fa * (1 / fb)33.4
  • v * (fa / fb)26.1

Two things surprised us. First, the drift does not grow forever. With civilDesk's form, every one of the 10 000 values reached its final position by lap 3 and stayed there through lap 1000. Even the worst strategy stops. The start value 854.698 drifts by one or two ULP per lap, reaches 49 ULP at lap 38 and then sits on a fixed point.

Line chart of the ULP distance from the start value 854.698 over 100 laps. The pair factor strategy climbs to 49 ULP by lap 38 and stays flat, while civilDesk's strategy stays at 1 ULP
ULP distance after each lap through five flow units, measured in Node 26.10.0

Second, the order of operations matters more than the number of hops. Precomputing a pair factor fa / fb looks like an optimisation, one multiplication instead of two operations, but it adds a third rounding that is baked into every call, and it is the version that drifts most. Multiplying by fa and dividing by fb keeps both constants exactly as written.

To keep it in proportion, 49 ULP at 854.698 is a relative error of 6.5e-15. No pipe in the world is built to that tolerance.

How to test floating point code with ULP and relative tolerance

expect(a).toBe(b) uses Object.is, so it demands the same double. That is right for an identity conversion and wrong for almost anything that calculates. The common fixes all have a catch.

Math.abs(a - b) < Number.EPSILON only makes sense near 1. At larger magnitudes it is stricter than the hardware can deliver. 1e6 * (0.1 + 0.2) is 300000.00000000006, off by 5.820766091346741e-11, which fails the epsilon check although it is the best a double can do. Near zero the same check is far too loose. Vitest's toBeCloseTo has the same problem in another form. toBeCloseTo(50, 12) passes when the difference is below 10^-12 / 2, an absolute tolerance. That is fine for a value around 50, meaningless for a flow of 1e-9 m³/s.

For conversions, the honest unit is the ULP, the number of representable doubles between the two values. civilDesk's spec measures it by reinterpreting the 64 bits as an integer.

ts
/** Distance between two doubles measured in units-in-the-last-place. */function ulpsApart(a: number, b: number): number {  if (a === b) return 0;  if (!Number.isFinite(a) || !Number.isFinite(b)) return Number.POSITIVE_INFINITY;  const buffer = new ArrayBuffer(8);  const floats = new Float64Array(buffer);  const ints = new BigInt64Array(buffer);  const asOrdered = (x: number): bigint => {    floats[0] = x;    const bits = ints[0]!;    // Map the sign-magnitude layout of IEEE-754 onto a monotonic integer line    // so that adjacent doubles are adjacent integers across zero.    return bits < 0n ? -(bits & 0x7fffffffffffffffn) : bits;  };  const diff = asOrdered(a) - asOrdered(b);  return Number(diff < 0n ? -diff : diff);}

This works because positive doubles sort the same way as their bit patterns read as integers, so adjacent doubles are adjacent integers. The one adjustment is for negative numbers, which IEEE 754 stores as sign and magnitude, so they are folded onto the negative side of the integer line.

Our own rule for conversions is strict. A value sent to the base unit and back must return within 1 ULP. flow-units.util.spec.ts states that rule literally and checks it over many inputs instead of three hand-picked ones.

ts
function* sampleFlows(): Generator<number> {  yield* [0, 1, 0.05, 0.5, 50, 1e-6, 1e-9, 123.456, 2.5e4, Number.MIN_VALUE, 1 / 3];  // Deterministic LCG sweep across ~14 orders of magnitude (no Math.random).  let seed = 20260806;  for (let i = 0; i < 500; i++) {    seed = (seed * 1103515245 + 12345) % 2147483648;    const mantissa = seed / 2147483648;    const exponent = (i % 28) - 14;    yield mantissa * 10 ** exponent;  }}it('display -> canonical -> display is within 1 ulp for every unit', () => {  for (const unit of ALL_UNITS) {    for (const v of sampleFlows()) {      const round = flowFromM3s(flowToM3s(v, unit), unit);      expect(ulpsApart(v, round), `${v} in ${unit} drifted`).toBeLessThanOrEqual(1);    }  }});

The generator is deterministic on purpose, so when a test fails, the seed alone reproduces it. The suite also runs a value through 1000 round trips and asserts it is still within one ULP of where it started, documents that a subnormal like Number.MIN_VALUE divided by 1000 underflows to zero, and checks that NaN and Infinity come out unchanged. All 16 tests pass in Vitest 4.1.10 in about 50 ms.

ULP is the right ruler for a single conversion. For the result of a calculation (a head loss, a pipe diameter) the errors of many operations add up, and the right ruler is a relative tolerance chosen from the problem. The helper below defaults to 1e-9 relative, far tighter than any engineering input, yet loose enough for a chain of a few dozen operations. You can drop it into any test.

ts
export function closeRel(a: number, b: number, rel = 1e-9, abs = 0): boolean {  if (a === b) return true; // also equal infinities  const diff = Math.abs(a - b);  return diff <= Math.max(rel * Math.max(Math.abs(a), Math.abs(b)), abs);}closeRel(0.1 + 0.2, 0.3);              // truecloseRel(1e6 * (0.1 + 0.2), 3e5);      // truecloseRel(1e-12, 0);                    // false: near zero you need an abs floor

NaN is never close to anything here, which is what you want. The abs floor exists because a relative tolerance against zero is zero. Pick it from the physics, the smallest flow that matters, not from Number.EPSILON.

Round only for display

Once the numbers are right, do not damage them on the way out. Rounding a stored value throws away information that the next calculation needed, and rounding in binary has its own surprises.

js
(1.005).toFixed(2);              // "1.00", because 1.005 is stored as 1.00499999999999989...Math.round(1.005 * 100) / 100;   // 1, because 1.005 * 100 is 100.49999999999999

MDN's page on toFixed explains the same effect. In civilDesk, rounding happens in exactly one place, the smartNumber pipe, at render time, with the user's chosen number of decimals.

ts
transform(value: number | null | undefined, overrideDecimals?: number, compact = false): string {  if (value == null || isNaN(value)) return '-';  // A diverging calculation must not render as the raw text "Infinity".  if (!Number.isFinite(value)) return value > 0 ? '∞' : '-∞';  const dp = overrideDecimals ?? this.settings.get('decimalPlaces');  // toFixed() turns ≥1e21 into raw exponent text; show huge magnitudes in a controlled form.  if (!compact && Math.abs(value) >= 1e12) return value.toExponential(Math.min(dp, 3));  const text = compact ? formatCompactNumber(value, Math.min(dp, 2)) : value.toFixed(dp);  // Tiny negatives (e.g. -0.0001 at 2 dp) round to "-0.00"; show them as zero.  return /^-0(\.0+)?$/.test(text) ? text.slice(1) : text;}

Each line answers a real display problem. A missing value shows as - rather than a believable 0.000, an overflow shows as ∞ rather than the word Infinity, and -0.00 never appears. The unit converter adds one more rule. When a non-zero result would display as zero at the chosen decimals, it switches to four significant digits with toPrecision(4), so 0.0000123 m³ at three decimals shows as 0.0000123 instead of 0.000. The value in memory, in the history and on the clipboard (toPrecision(8)) keeps its full precision.

A checklist for unit conversion in JavaScript

  1. Pick one canonical unit per quantity and store only that. Convert once on input and once on output.
  2. Write constants as exact decimal literals from their definitions, and never compute them with ** or chains of multiplications.
  3. Prefer dividing by an exact integer over multiplying by its reciprocal, and multiply by fa then divide by fb instead of precomputing fa / fb.
  4. Write user-facing presets and validator bounds as authored pairs, not as converted values.
  5. Never compare computed doubles with === or toBe. Use ULP distance for conversions and a relative tolerance (with an absolute floor near zero) for physics.
  6. Test over a deterministic generator across many magnitudes, including 0, subnormals, NaN and Infinity.
  7. Round in the view layer only, and decide what NaN, Infinity and -0 should look like.

If you have a conversion table in your own code, the most useful hour you can spend today is to open it, check every constant against its definition, and add one round-trip test with ulpsApart over a few hundred generated values. It will either pass and let you stop worrying, or show you exactly where the drift comes from. The calculators that use this code are in civilDesk.

Topics:#javascript#floating-point#testing#unit-conversion

Written by

Amin Norollah

Full-stack developer and team lead with 14+ years in software: .NET, Java and Node.js backends, Angular front ends, and systems for payments, trading and industry. Before that, a researcher at IUST with Université Grenoble Alpes, with 13 papers (IEEE, Elsevier) on hardware security, real-time scheduling and network-on-chip.

norollah.com
How to cite this article

Amin Norollah, "Why 0.1 + 0.2 breaks unit conversion in JavaScript", toyfox blog, December 2, 2026, https://toyfox.app/en/blog/floating-point-unit-conversion-javascript/

Live

Offline calculators for civil and electrical engineers

More than 45 offline engineering calculators for hydraulics, structures, geotechnics, roads, surveying and electrical work, with animated 3D models and building code references.

All posts
civilDesk on Google Play

Announcement1 min read

civilDesk is coming to Google Play

Offline calculators for civil engineers, with more than 350 building code clauses from Iran, the US, Europe, Sweden and Spain.

civilDesk