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.
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.
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.
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.
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. */exportconstLITRES_PER_CUBIC_METRE=1000;exportfunctionflowToM3s(value:number, unit:FlowUnit):number {if (!Number.isFinite(value)) return value;return unit ==='l/s'? value /LITRES_PER_CUBIC_METRE: value;}exportfunctionflowFromM3s(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.
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.
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.tsconstsi= v * from.factor; // toBaseconstout= 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.
Strategy
Exact after 1 lap
Within 1 ULP after 10 laps
Worst 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 factor
26.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.
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. */functionulpsApart(a:number, b:number):number {if (a === b) return0;if (!Number.isFinite(a) ||!Number.isFinite(b)) return Number.POSITIVE_INFINITY;constbuffer=newArrayBuffer(8);constfloats=newFloat64Array(buffer);constints=newBigInt64Array(buffer);constasOrdered= (x:number):bigint=> { floats[0] = x;constbits= 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; };constdiff=asOrdered(a) -asOrdered(b);returnNumber(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;constmantissa= seed /2147483648;constexponent= (i %28) -14;yield mantissa *10** exponent; }}it('display -> canonical -> display is within 1 ulp for every unit', () => {for (constunitofALL_UNITS) {for (constvofsampleFlows()) {constround=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
exportfunctioncloseRel(a:number, b:number, rel=1e-9, abs=0):boolean {if (a === b) returntrue; // also equal infinitiesconstdiff= 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?'∞':'-∞';constdp= 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));consttext= 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
Pick one canonical unit per quantity and store only that. Convert once on input and once on output.
Write constants as exact decimal literals from their definitions, and never compute them with ** or chains of multiplications.
Prefer dividing by an exact integer over multiplying by its reciprocal, and multiply by fa then divide by fb instead of precomputing fa / fb.
Write user-facing presets and validator bounds as authored pairs, not as converted values.
Never compare computed doubles with === or toBe. Use ULP distance for conversions and a relative tolerance (with an absolute floor near zero) for physics.
Test over a deterministic generator across many magnitudes, including 0, subnormals, NaN and Infinity.
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.
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.
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.
One add_header in an nginx location drops every header set above it. Here is the inheritance rule, a curl check, and how we ended up sending HSTS twice.
No sound on Android with @capacitor-community/native-audio? Prefix assetPath with public/ and start loops with play(), since loop() in 8.0.0 never resolves.