Why does `0.1 + 0.2 === 0.3` return false in JavaScript?
poze 5 months ago206 gadeen
I was writing a small invoice calculator and this check fails:
console.log(0.1 + 0.2 === 0.3); // false
console.log(0.1 + 0.2); // 0.30000000000000004
Is this a bug in JavaScript? How should I compare or add money amounts?
Dyagnostik IA
Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.
2 Repons
It's not a JavaScript bug. It's how IEEE-754 binary floating point works, and Python, Java and C# do exactly the same thing. 0.1 has no exact binary representation, so tiny rounding errors show up.
Comparing floats: use a tolerance.
const nearlyEqual = (a, b) => Math.abs(a - b) < Number.EPSILON * 10;
nearlyEqual(0.1 + 0.2, 0.3); // true
Money: never store it as floating point. Store integer cents (or the smallest unit, e.g. centimes of a gourde):
const totalCents = 1050 + 299; // 13.49
const display = (totalCents / 100).toFixed(2);
For heavy financial math, use a decimal library such as decimal.js, or do it in the database with a NUMERIC column.
Konekte pou di lòt moun si li te mache.
To add to the accepted answer: toFixed is fine for display but returns a string and does its own rounding. Intl.NumberFormat is the better formatter:
new Intl.NumberFormat('fr-HT', { style: 'currency', currency: 'HTG' }).format(13.49);Konekte pou di lòt moun si li te mache.
Sign in and verify your email to post an answer.