Javascript函数格式化为货币

Javascript Function to Format as Money

本问题已经有最佳答案,请猛点这里访问。

我有一个脚本,我传给它一个字符串,它将返回格式为美元的字符串。 因此,如果我发送它"10000"它将返回"$ 10,000.00"现在的问题是,当我发送它"1000000"(100万美元)时,它返回"$ 1,000.00",因为它只设置为基于一组零进行解析。 这是我的脚本,如何调整它以占两组零(100万美元)?

1
2
3
4
5
6
7
8
9
10
11
12
13
String.prototype.formatMoney = function(places, symbol, thousand, decimal) {
if((this).match(/^\$/) && (this).indexOf(',') != -1 && (this).indexOf('.') != -1) {
    return this;
}
    places = !isNaN(places = Math.abs(places)) ? places : 2;
    symbol = symbol !== undefined ? symbol :"$";
    thousand = thousand ||",";
    decimal = decimal ||".";
var number = Number(((this).replace('$','')).replace(',','')),
    negative = number < 0 ?"-" :"",
    i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) +"",
    j = (j = i.length) > 3 ? j % 3 : 0;
return negative + symbol + (j ? i.substr(0, j) + thousand :"") + i.substr(j).replace(/(\d{3})(?=\d)/g,"$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) :""); };

提前感谢任何有用的信息!


1
2
3
4
5
6
function formatMoney(number) {
  return number.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
}

console.log(formatMoney(10000));   // $10,000.00
console.log(formatMoney(1000000)); // $1,000,000.00

给它一个镜头,它寻找一个小数分隔符但你可以删除该部分,如果你喜欢:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
    {
      number = parseFloat(number);
      //if number is any one of the following then set it to 0 and return
      if (isNaN(number)) {
        return ('0' + '{!decimalSeparator}' + '00');
      }

      number = Math.round(number * 100) / 100; //number rounded to 2 decimal places
      var numberString = number.toString();
      numberString = numberString.replace('.', '{!decimalSeparator}');

      var loc = numberString.lastIndexOf('{!decimalSeparator}'); //getting position of decimal seperator
      if (loc != -1 && numberString.length - 2 == loc) {
        //Adding one 0 to number if it has only one digit after decimal
        numberString += '0';
      } else if (loc == -1 || loc == 0) {
        //Adding a decimal seperator and two 00 if the number does not have a decimal separator
        numberString += '{!decimalSeparator}' + '00';
      }
      loc = numberString.lastIndexOf('{!decimalSeparator}'); //getting position of decimal seperator id it is changed after adding 0
      var newNum = numberString.substr(loc, 3);
      // Logic to add thousands seperator after every 3 digits
      var count = 0;
      for (var i = loc - 1; i >= 0; i--) {
        if (count != 0 && count % 3 == 0) {
          newNum = numberString.substr(i, 1) + '{!thousandSeparator}' + newNum;
        } else {
          newNum = numberString.substr(i, 1) + newNum;
        }
        count++;
      }

// return newNum if youd like
    };