格式化为货币的Javascript函数

Javascript Function to Format as Money

本文关键字:Javascript 函数 货币 格式化      更新时间:2023-09-26

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

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) : ""); };

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

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

试试它会寻找一个小数分隔符但如果你愿意,你可以删除这部分:

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