Fixing issue in javascript number operation using toFixed() method in javascript.

Lets look into the problem which might arise while performing addition and substraction in javascript. Try the mentioned below code in your browser console or any javascript runtime e.g. Nodejs console.

5.1 + 3.3 // expected output is 8.4 but if you check you will get 8.399999999999999

3.8 - 2.1 // expected output is 1.7 but if you check you will get 1.6999999999999997

The above code will create a big problem incase of comparison of value’s so to fix the above problem we can use toFixed(number) method which accepts a value which rounds to that number of decimal places.

(5.1 + 3.3).toFixed(2) // expected output is 8.4 and result is "8.4"

(3.8 - 2.1).toFixed(2) // expected output is 1.7 and result is "1.7"

Note: The output of the above operation is of type string, so if you compare using ‘==’ result is true but if you use ‘===’ result is false because ‘===’ checks the data type of the variable also.