Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
}
like image 980
user610728 Avatar asked Feb 17 '11 04:02

user610728


1 Answers

New 2016 solution

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

Do not forget to include polyfill.

  • compat table
  • API docs

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?

like image 160
kirilloid Avatar answered Oct 05 '22 21:10

kirilloid