Monday, 6 March 2017

rounding - Formatting a number with exactly two decimals in JavaScript




I have this line of code which rounds my numbers to two decimal places. But I get numbers like this: 10.8, 2.4, etc. These are not my idea of two decimal places so how I can improve the following?



Math.round(price*Math.pow(10,2))/Math.pow(10,2);


I want numbers like 10.80, 2.40, etc. Use of jQuery is fine with me.


Answer



To format a number using fixed-point notation, you can simply use the toFixed method:



(10.8).toFixed(2); // "10.80"


var num = 2.4;
alert(num.toFixed(2)); // "2.40"


Note that toFixed() returns a string.



IMPORTANT: Note that toFixed does not round 90% of the time, it will return the rounded value, but for many cases, it doesn't work.



For instance:




2.005.toFixed(2) === "2.00"





Nowadays, you can use the Intl.NumberFormat constructor. It's part of the ECMAScript Internationalization API Specification (ECMA402). It has pretty good browser support, including even IE11, and it is fully supported in Node.js.





const formatter = new Intl.NumberFormat('en-US', {

minimumFractionDigits: 2,
maximumFractionDigits: 2,
});

console.log(formatter.format(2.005)); // "2.01"
console.log(formatter.format(1.345)); // "1.35"






You can alternatively use the toLocaleString method, which internally will use the Intl API:





const format = (num, decimals) => num.toLocaleString('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});



console.log(format(2.005)); // "2.01"
console.log(format(1.345)); // "1.35"





This API also provides you a wide variety of options to format, like thousand separators, currency symbols, etc.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...