Join waitlist
JavaScriptCommunity question

0.1 + 0.2 != 0.3 but 0.25 + 0.5 == 0.75?

Asked by Karthik Rajan 1 month ago 2 answers 8 votes

I know "floating point" is the answer but why does it break for 0.1 and 0.2 and not for 0.25 and 0.5

2 answers

Sid Rao1 month agoMost voted7

Binary can only store fractions exactly if the denominator is a power of 2.

0.25 = 1/4, 0.5 = 1/2, both exact, so the sum is exact.

0.1 = 1/10, and 10 has a factor of 5. In binary it becomes a repeating fraction (like 1/3 in decimal), so it gets rounded when stored. Same for 0.2. The two rounding errors add up and you get 0.30000000000000004.

For money just use integers (paise).

Sanjana Hegde1 month ago2

this is also why DECIMAL exists in databases. never store money in float

Related questions

Go deeper

Want the full explanation, not just an answer?

Structured lessons on DSA, core CS, Java and interview skills, each ending in a quiz so you know it stuck.