Sushovan Mukherjee Sushovan Mukherjee - 4 years ago 275
Javascript Question

Javascript toFixed function

The expected result of:

(1.175).toFixed(2) = 1.18 and
(5.175).toFixed(2) = 5.18


But in JS showing:

(1.175).toFixed(2) = 1.18 but
*(5.175).toFixed(2) = 5.17*


How to rectify the problem?

Answer Source

You could always try using round, instead of toFixed.

Math.round(5.175*100)/100

You could even try putting it in some prototype method if you want.

Created a jsBin that implements a simple prototype on Number.

Number.prototype.toFixed = function(decimals) {
 return Math.round(this * Math.pow(10, decimals)) / (Math.pow(10, decimals)); 
};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download