JavaScript Floating Point Precision Issue

Today, I learned something interesting about numbers in JavaScript. For example: 0.1 + 0.2 = 0.30000000000000004  But 1.1 plus 1.2 equals 2.3 In simple terms: JavaScript doesn't store numbers in decimal form; it stores them in binary (0s and 1s). Binary can't store some decimal numbers exactly, like 0.1 and 0.2. This means that a very small error is added when you do math. That's why you might see results like 0.30000000000000004. Temporary Fixes : Use Math.round : Math.round((0.1 + 0.2) * 100) / 100  Use toFixed:  (0.1 + 0.2).toFixed(2)  Use Math.floor or Math.ceil: Math.floor((0.1 + 0.2) * 100) / 100  //when rounding off lower value Math.ceil((0.1 + 0.2) * 100) / 100 //when rounding off to upper value This is not a bug in JavaScript. It happens because of how most programming languages store floating-point numbers. #JavaScript #Coding #WebDevelopment #Programming #100DaysOfCode

  • graphical user interface, application

To view or add a comment, sign in

Explore content categories