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.
To format a number using fixed-point notation, you can simply use the toFixed method:
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"UPDATE:
Nowadays, you can use the
Intl.NumberFormatconstructor. 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.You can alternatively use the
toLocaleStringmethod, which internally will use theIntlAPI:This API also provides you a wide variety of options to format, like thousand separators, currency symbols, etc.