【问题标题】:Javascript Function to Format as Money [duplicate]格式化为货币的Javascript函数[重复]
【发布时间】:2017-03-18 12:58:49
【问题描述】:

我有一个脚本,我向它传递一个字符串,它会返回格式化为美元的字符串。因此,如果我发送它“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) : ""); };

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

【问题讨论】:

  • 使用循环。每当您需要重复代码时,请使用循环。
  • 一般来说:这是很常见的事情,很可能存在您应该使用的 API 或库,而不是重新发明这个特定的轮子。

标签: javascript


【解决方案1】:
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

【讨论】:

  • 令我惊讶的是,Javascript 没有我所在国家/地区货币代码的货币符号,因此它通过错误或返回错误符号。我认为下面的这个解决方案更通用,因此您可以使用 HTML const price = 1470000.15 添加任何货币符号;让 formatMoney= Intl.NumberFormat('en-IN'); console.log("美国语言环境输出:" + formatMoney.format(price));
【解决方案2】:

试一试,它会查找小数分隔符,但如果您愿意,可以删除该部分:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    相关资源
    最近更新 更多