仅使用Javascript格式化数字为千
Console.log
显示正确的结果,但如何在键入时为输入类型添加相同的格式。
每个逗号后,输入类型将重置为零。
1000至1,000
请帮忙。
这段代码在这里工作
function numberWithCommas(number) { if (isNaN(number)) { return ''; } var asString = '' + Math.abs(number), numberOfUpToThreeCharSubstrings = Math.ceil(asString.length / 3), startingLength = asString.length % 3, substrings = [], isNegative = (number 0) { substrings.push(asString.substring(0, startingLength)); } for (i=startingLength; i < asString.length; i += 3) { substrings.push(asString.substr(i, 3)); } formattedNumber = substrings.join(','); if (isNegative) { formattedNumber = '-' + formattedNumber; } document.getElementById('test').value = formattedNumber; }
一些说明:
- 因为你想要逗号,所以类型不是数字,它是一个字符串
- 因为你想在键入后处理输入,所以onkeyup不是onkeypressed
我有一个解决方案,使用3个字符替换3个字符的正则表达式加上逗号:
var x = "1234567"; x.replace(/.../g, function(e) { return e + ","; } ); // Gives: 123,456,7
即几乎正确的答案,但逗号不在正确的位置。 所以让我们用String.prototype.reverse()
函数修复它:
String.prototype.reverse = function() { return this.split("").reverse().join(""); } function reformatText() { var x = document.getElementById('test').value; x = x.replace(/,/g, ""); // Strip out all commas x = x.reverse(); x = x.replace(/.../g, function(e) { return e + ","; } ); // Insert new commas x = x.reverse(); x = x.replace(/^,/, ""); // Remove leading comma document.getElementById('test').value = x; }
function numberWithCommas(x) { var real_num = x.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"); console.log(real_num); document.getElementById('test').value = real_num; }
看看我的小提琴http://jsfiddle.net/6cqn3uLf/你需要另一个正则表达式来限制数字,但这将根据用户的语言环境进行格式化 – 这在这里可能是有利的。
$(function(){ $('#btnformat')。on('input propertychange paste',function(){ var x = $('#btnformat')。val(); $( '#btnformat')VAL(号码(x.replace(/,/克, ''))的toLocaleString()); }); });
如果jquery不是您的应用程序的开销,那么您可以使用https://code.google.com/p/jquery-numberformatter/