Javascript函数格式化为货币

时间:2016-11-04 15:55:59

标签: javascript

我有一个脚本,我在其中传递一个字符串,然后它将返回格式为美元的字符串。所以,如果我发送它" 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) : ""); };

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

2 个答案:

答案 0 :(得分: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 :(得分:1)

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

&#13;
&#13;
	{
	  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
	};
&#13;
&#13;
&#13;