Why Does 2.3 + 0.4 Equal 2.6999999999999997 Instead of 2.7?

April 18, 2025 5 answers
Asked by PITCH..count
I'm puzzled why adding 2.3 and 0.4 in JavaScript results in 2.6999999999999997 instead of the expected 2.7. Can anyone explain what's going on with this calculation?

Answers

algebra scratchwork
This is actually a common issue with floating-point arithmetic in programming. JavaScript uses the IEEE 754 standard for representing numbers, which can lead to precision errors. When you try to represent certain decimal numbers in binary, they canโ€™t be expressed accurately, resulting in unexpected outputs like this. You can read more about it on the Wikipedia page about IEEE 754 if you're interested.

talc.: For a simpler explanation tailored to this specific issue, check out the site 0.30000000000000004.com. It breaks it down nicely!

Reply to this answer
rain8mm
Computers operate using base 2, so numbers like 2.3 or 0.4 canโ€™t be precisely represented, leading to a loss of precision. Just like how 1/3 canโ€™t be perfectly expressed in decimal form, these fractions in binary result in an infinite form. It's a general issue across any language using standard CPU floating points, not just JavaScript.
Reply to this answer
!+gentle acceleration
This comes down to what seems like a floating-point error. What youโ€™re seeing is a tiny calculation error typical in decimal arithmetic on computers. Essentially, some numbers canโ€™t be represented precisely, especially in binary.
Reply to this answer
3ch-gainStage
If you're dealing with money calculations or need more precision, avoid using floats directly. A common workaround is to multiply your values (like by 100 for cents) before doing arithmetic. This reduces the chances of these weird floating-point results.

grade-2pct: JavaScript doesnโ€™t differentiate between number types and always uses double precision floating points. Thatโ€™s why this happens!

Reply to this answer
7th inning stretch
Programs handle decimals differently, which leads to normalized fractions in languages like JavaScript. When performing calculations, you might end up with tiny precision errors like this one. If you're frequently working with decimal fractions, consider using specialized libraries like decimals.js for better accuracy.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions