我想用JavaScript格式化价格。我想要一个函数,它将浮点作为参数,并返回如下格式的字符串:

"$ 2,500.00"

我该怎么做?


当前回答

只需使用本机javascript Intl

您只需使用选项设置其值的格式

常量编号=1233445.5678console.log(新的Intl.NumberFormat('en-US',{style:'currency',currency:'USD'}).format(数字));

mozilla文档链接

其他回答

这是我的。。。

function thousandCommas(num) {
  num = num.toString().split('.');
  var ints = num[0].split('').reverse();
  for (var out=[],len=ints.length,i=0; i < len; i++) {
    if (i > 0 && (i % 3) === 0) out.push(',');
    out.push(ints[i]);
  }
  out = out.reverse() && out.join('');
  if (num.length === 2) out += '.' + num[1];
  return out;
}

数字(值).to固定(2).replace(/(\d)(?=(\d{3})+(?!\d))/g,“$1,”)

使用正则表达式的较短方法(用于插入空格、逗号或点):

    Number.prototype.toCurrencyString = function(){
        return this.toFixed(2).replace(/(\d)(?=(\d{3})+\b)/g, '$1 ');
    }

    n = 12345678.9;
    alert(n.toCurrencyString());

我喜欢简单:

function formatPriceUSD(price) {
    var strPrice = price.toFixed(2).toString();
    var a = strPrice.split('');

    if (price > 1000000000)
        a.splice(a.length - 12, 0, ',');

    if (price > 1000000)
        a.splice(a.length - 9, 0, ',');

    if (price > 1000)
        a.splice(a.length - 6, 0, ',');

    return '$' + a.join("");
}

以下是将数字转换为货币格式的简短最佳方法:

function toCurrency(amount){
    return amount.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}

// usage: toCurrency(3939920.3030);