在javascript中动态地重新格式化输入,为数字添加逗号

dynamically reformat input in javascript to add commas to numbers

本文关键字:数字 添加 输入 格式化 javascript 动态      更新时间:2023-09-26

我有一个数字输入问题。用户通常输入一个带有许多零的大数字,而且他们经常会少一两个零,因为很难准确地计数。

我认为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的搜索结果中出现的,所以我想我需要添加一个更短更好的答案。