我一直试图想出一种方法,而不使用某人的插件将带小数的数字格式化为无小数的货币。我发现以下是迄今为止最简单的方法:
yourVar.toLocaleString("en", { style: 'currency', currency: 'USD' }).split('.')[0]
示例:
before:446882086.00
after:$446,882,086
答案 0 :(得分:0)
在此问题的帮助下:Add commas or spaces to group every three digits
我创建了这个功能:
function convertString(currency, input) {
var thisInt = Math.round(input); //this removes numbers after decimal
var thisOutputValue = currency + commafy(thisInt); //add currency symbol and commas
return thisOutputValue;
}
function commafy(num) {
var str = num.toString().split('.');
if (str[0].length >= 5) {
str[0] = str[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,');
}
if (str[1] && str[1].length >= 5) {
str[1] = str[1].replace(/(\d{3})/g, '$1 ');
}
return str.join('.');
}
var changeIntToCurrencyString = convertString('$', 435345.00) //change numbers into dollars
console.log(changeIntToCurrencyString )
以上代码将整数435345.00
转换为美元货币字符串:$435,345
。它应该适用于所有其他整数值:)
小提琴:https://jsfiddle.net/thatOneGuy/zL817x5a/3/
function convertString(currency, input) {
var thisInt = Math.round(input); //this removes numbers after decimal
var thisOutputValue = currency + commafy(thisInt); //add currency symbol and commas
return thisOutputValue;
}
function commafy(num) {
var str = num.toString().split('.');
if (str[0].length >= 5) {
str[0] = str[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,');
}
if (str[1] && str[1].length >= 5) {
str[1] = str[1].replace(/(\d{3})/g, '$1 ');
}
return str.join('.');
}
var tryoutint = 435345.00;
var changeIntToCurrencyString = convertString('$', tryoutint) //change numbers into dollars
console.log(changeIntToCurrencyString)
alert(tryoutint + ' : ' + changeIntToCurrencyString)