user610728 - 1 year ago 114
jQuery Question

# Javascript Number formatting min/max decimals

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;
}
}
``````

### New 2016 solution

``````value.toLocaleString('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 4
});
``````

Do not forget to include polyfill.

### Old 2011 solution

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?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download