开发者

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)) {
      开发者_JS百科      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.

  • 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?


You're doing it wrong.

54433.6559943.toFixed(4) will round to 4 places. You then have to trim off up to two trailing zeroes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜