I would like to format my numbers to always display 2 decimal places, rounding where applicable.
Examples:
number display
------ -------
1
(Math.round(num * 100) / 100).toFixed(2);
Live Demo
var num1 = "1";
document.getElementById('num1').innerHTML = (Math.round(num1 * 100) / 100).toFixed(2);
var num2 = "1.341";
document.getElementById('num2').innerHTML = (Math.round(num2 * 100) / 100).toFixed(2);
var num3 = "1.345";
document.getElementById('num3').innerHTML = (Math.round(num3 * 100) / 100).toFixed(2);
span {
border: 1px solid #000;
margin: 5px;
padding: 5px;
}
<span id="num1"></span>
<span id="num2"></span>
<span id="num3"></span>
Note that it will round to 2 decimal places, so the input 1.346
will return 1.35
.
var number = 123456.789;
console.log(new Intl.NumberFormat('en-IN', { maximumFractionDigits: 2 }).format(number));
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
Convert a number into a string, keeping only two decimals:
var num = 5.56789;
var n = num.toFixed(2);
The result of n will be:
5.57
Where specific formatting is required, you should write your own routine or use a library function that does what you need. The basic ECMAScript functionality is usually insufficient for displaying formatted numbers.
A thorough explanation of rounding and formatting is here: http://www.merlyn.demon.co.uk/js-round.htm#RiJ
As a general rule, rounding and formatting should only be peformed as a last step before output. Doing so earlier may introduce unexpectedly large errors and destroy the formatting.
You can try this code:
function FormatNumber(number, numberOfDigits = 2) {
try {
return new Intl.NumberFormat('en-US').format(parseFloat(number).toFixed(2));
} catch (error) {
return 0;
}
}
var test1 = FormatNumber('1000000.4444');
alert(test1); // 1,000,000.44
var test2 = FormatNumber(100000000000.55555555, 4);
alert(test2); // 100,000,000,000.56
function currencyFormat (num) {
return "$" + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
}
console.info(currencyFormat(2665)); // $2,665.00
console.info(currencyFormat(102665)); // $102,665.00