在javascript中动态地重新格式化输入,为数字添加逗号
dynamically reformat input in javascript to add commas to numbers
我有一个数字输入问题。用户通常输入一个带有许多零的大数字,而且他们经常会少一两个零,因为很难准确地计数。
我认为javascript可以通过向用户显示他们输入的数字来解决这个问题,用逗号格式化。
,
输入:| 1230000000000 |
Result: 1,23,000,000,000
这是怎么做到的?
在javascript中使用以下函数
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /('d+)('d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
例子addCommas('9999999.00')
// 9,999,999.00
这是一个老问题,但仍然没有正确的答案,所以,这是我的动态解决方案,它需要相同的addcomma函数来重新格式化输出,但添加一个keyup事件来清理当前值(删除',')并重新格式化新值。
$('.datainto').keyup(function () {
var value = $(this).val().replace(/,/g,'');
$(this).val(addCommas(value));
});
检查工作解决方案在这里:http://jsfiddle.net/darorck/371zrjet/
function formatNumber() {
// select the input box
let numInput = document.getElementById("myNumberInput");
//get the value from the selected input box, remove commas
//and convert it into float
let num = parseFloat(numInput.value.replace(/,/g, ""));
//replace the value in the input box with comma separated value
//only if it is a valid number
if (!isNaN(num)) {
let formattedNum = num.toLocaleString('en-US');
numInput.value = formattedNum;
} else {
numInput.value = "";
}
}
<input type="text" id="myNumberInput" onkeyup="formatNumber()" />
在现代浏览器中,您可以简单地使用toLocaleString()
console.log((1230000000000).toLocaleString());
console.log((12300000000).toLocaleString());
console.log((1230000.152).toLocaleString());
我知道我很晚才给出答案,但是,我还是发布了这个答案,因为这个问题是在How to add a dynamic comma in number in javascript
的搜索结果中出现的,所以我想我需要添加一个更短更好的答案。
相关文章:
- 在 Javascript 不起作用的情况下为数字添加逗号
- 如何在 javascript 中为字符串中的数字添加下划线
- 将数字添加到文本框
- 使用javascript为网站的body标记中的所有数字添加一个span
- 如何在文本框vue.js上根据指定的数字添加行
- AngularJS如何获取一个数组,该数组将数字添加到函数中的元素,然后用另一个函数分散其注意力
- 使用 Jquery 为数字添加跨度
- 向数字添加百分之一位,该数字可以逗号或句点分隔
- 根据所选数字添加文本输入
- 将 JavaScript 数组中的 n 个数字添加到数组中的先前数字
- 有没有办法在不使用循环的情况下更新多个文档以将特定数字添加到一列
- 在javascript中自动为数字添加逗号
- Javascript:如何动态地将数字添加到变量名称中
- JQuery 获取链接并根据第 n 个数字添加变量
- 在 jquery 循环中将数字添加到运行总计
- 将字符串添加到数字,将数字添加到字符串
- 如何使用jquery将数字添加到输入ID名称中
- 我有一个javascript函数,可以将数字添加到数组中
- 如何在JS计数器中每3个数字添加一个冒号
- 只对大写字母和数字添加验证