numFormat k m html script code example
Example 1: js format urcurency
// Create our number formatter.
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
});
formatter.format(2500); /* $2,500.00 */
Example 2: javascript convert number from thousands to k and millions to m
// converts number to string representation with K and M.
// toFixed(d) returns a string that has exactly 'd' digits
// after the decimal place, rounding if necessary.
function numFormatter(num) {
if(num > 999 && num < 1000000){
return (num/1000).toFixed(1) + 'K'; // convert to K for number from > 1000 < 1 million
}else if(num > 1000000){
return (num/1000000).toFixed(1) + 'M'; // convert to M for number from > 1 million
}else if(num < 900){
return num; // if value < 1000, nothing to do
}
}