我设法将用户输入设为2个小数点: 下面是我的两个输入字段的代码:
$('.ave-daily-accbalance').blur(function(){
var num = parseFloat($(this).val()) || 0;
var cleanNum = num.toFixed(2);
$(this).val(cleanNum);
});
$('.facilitylimit').blur(function(){
var num = parseFloat($(this).val()) || 0;
var cleanNum = num.toFixed(2);
$(this).val(cleanNum);
});
但现在我想用逗号分隔输入。因此,如果用户输入500000 - 它会自动转换为500,000.00
答案 0 :(得分:2)
您可以使用Number.prototype.toLocaleString()
(documentation)
在您的情况下,您希望使用第二个选项参数来指定所需的小数点数:
var num = 200000.001231;
var cleanNum = num.toLocaleString('en', {minimumFractionDigits: 2, maximumFractionDigits: 2});
console.log(cleanNum);

请注意,options参数不适用于所有浏览器和版本。如果兼容性是关键,则使用不带参数的num.toLocaleString()
,并根据需要修剪/附加小数:
var num = 20000.001231;
var cleanNum = num.toLocaleString('en');
var splitNum = cleanNum.split('.');
if (splitNum.length < 2) {
// Need to append .00 if num was an integer
cleanNum = cleanNum + '.00';
} else {
// Append 0 if there was only 1 decimal, otherwise trim
// to 2 decimals
var decimals = splitNum[1];
decimals = decimals.length < 2 ? decimals + '0' : decimals.slice(0, 2);
cleanNum = splitNum[0] + '.' + decimals;
}
console.log(cleanNum);
&#13;
希望这有帮助!
答案 1 :(得分:1)
这个解决方案怎么样?希望它有所帮助!
var x = 500000;
function formatNumber(num) {
var arr = num.toFixed(2).split(".");
return arr[0].split("").reduceRight(function(acc, num, i, orig) {
if ("-" === num && 0 === i) {
return num + acc;
}
var pos = orig.length - i - 1
return num + (pos && !(pos % 3) ? "," : "") + acc;
}, "") + (arr[1] ? "." + arr[1] : "");
}
console.log(formatNumber(x));
答案 2 :(得分:0)
试试这个:
var n = "76432949.13354";
var nf = Number(parseFloat(n).toFixed(2)).toLocaleString('en');
document.write (nf);
&#13;