Ad space (banner)
🟨JavaScript Lessons
Lesson 58 / 69

Watch Out for Floating-Point Rounding Error

In this lesson you'll learn about the error that occurs when a computer handles decimal numbers, so you can understand the points to watch for in things like money calculations. This is for people searching "JavaScript 0.1 0.2 floating point error."

Because a computer represents decimal numbers in binary, even a simple calculation like 0.1 + 0.2 doesn't come out to exactly 0.3. Displaying it shows the error directly, and comparing it returns false. This isn't unique to JavaScript — it stems from how computers work under the hood, common across many programming languages.

The sample code shows that running 0.1 + 0.2 displays a value with error included, 0.30000000000000004, and that the comparison 0.1 + 0.2 === 0.3 comes out false. This is one of the first things that surprises programming beginners, and it's an experience that overturns the assumption that "computer calculations are always exact."

When decimal error becomes a problem for money calculations, you need some way to avoid it, such as calculating using integer cents instead of dollars-and-cents decimals. Instead of comparing decimals directly, a common approach is to allow a small tolerance — treating two values as equal if the difference between them is extremely small.

In situations demanding severe precision, like money calculations, taking this characteristic into account is essential. In accounting systems and e-commerce price calculations, this kind of error can create unexpected discrepancies in amounts, so in real projects it's common to use a dedicated library or integer-based calculations.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)