I'm trying to create a function that can format a number with the minimum decimal places of 2 and a maximum of 4. So basically if I pass in 354545.33 I would get back 354,545.33 and if I pass in 54433.6559943 I would get back 54,433.6559.
function numberFormat(num){
num = num+"";
if (num.length > 0){
num = num.toString().replace(/\$|\,/g,'');
num = Math.floor(num * 10000) / 10000;
num += '';
x = num.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
else{
return num;
}
}
value.toLocaleString('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 4
});
Do not forget to include polyfill.
To format a part, after decimal point you can use this:
value.toFixed(4).replace(/0{0,2}$/, "");
And for part before decimal point: How to write this JS function in best(smartest) way?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With