What Will 0.1 + 0.2 Be in JavaScript? Why?

September 27, 2022

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

JavaScript, like most programming languages, produces a strange number when we add 0.1 + 0.2, which can cause errors if not handled properly. This is a problem that must be avoided for products that require high numerical precision, such as financial products. Therefore, this is also a common basic question in JavaScript interviews.

What will 0.1 + 0.2 be in JavaScript?

It will be 0.30000000000000004

Why does 0.1 + 0.2 equal 0.30000000000000004?

This is not a unique phenomenon in JavaScript, but a problem encountered by all programming languages that use binary floating-point operations. JavaScript uses IEEE 754 64-bit double precision floating-point numbers, which is why this problem occurs when working with decimal points.

In everyday life, we mostly use decimal, and to accurately express decimal, 10's factors are 5 and 2, so only 1/2, 1/4, 1/5, 1/8, 1/10 can be clearly expressed by decimal; but 1/3, 1/6, 1/7, 1/9 cannot. For example, we know that 1/3 will be 0.33333333 endlessly.

For binary, only 1/2, 1/4, 1/8 can be clearly expressed, while others will continue endlessly. However, because the computer's memory is limited and the program language assigns a limited amount of memory to a number, there are limitations in the expression of accuracy, which is the reason for the strange number 0.30000000000000004.

How to avoid related problems?

How to avoid related problems? In JavaScript, there are methods such as toFixed and toPrecision for manipulating numbers, which allow us to set the precision we want. For example, we can set the precision to the first decimal place.

console.log((0.1 + 0.2).toFixed(1)); // 0.3
console.log((0.1 + 0.2).toPrecision(1)); // 0.3

Alternatively, you can use some popular JavaScript libraries. The following are a few that are popular on GitHub.

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee