简体   繁体   English

在 javascript 中动态重新格式化输入以将逗号添加到数字

[英]dynamically reformat input in javascript to add commas to numbers

I have an issue with number inputting.我在输入数字时遇到问题。 The user usually enters a large number with many zeros, and often they are missing one or two zero as it is difficult to accurately count them.用户通常输入一个带有许多零的大数字,并且由于难以准确计算它们而经常丢失一个或两个零。

I think javascript can work this out by showing the user the number they have inducted, formatted with commas.我认为 javascript 可以通过向用户显示他们感应到的数字来解决这个问题,用逗号格式化。

eg:例如:

input: |输入:| 1230000000000 | 1230000000000 |

Result: 1,230,000,000,000结果:1,230,000,000,000

How could this be accomplished?这怎么可能实现?

Use the following function in javascript在 javascript 中使用以下 function

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;
}

example例子

addCommas('9999999.00')
// 9,999,999.00

This is an old question but still without a correct answer so, this is my dynamic solution, it takes the same addCommas function to reformat the output but add a keyup event to clean the current value ( remove ',' ) and reformat again the new value.这是一个老问题,但仍然没有正确答案,所以这是我的动态解决方案,它需要相同的 addCommas function 来重新格式化 output 但添加一个 keyup 事件来清除当前值(删除 ',' )并再次重新格式化新的价值。

$('.datainto').keyup(function () {
    var value = $(this).val().replace(/,/g,'');
    $(this).val(addCommas(value));
});

Check the working solution here: http://jsfiddle.net/darorck/371zrjet/在此处检查工作解决方案: http://jsfiddle.net/darorck/371zrjet/

In modern browsers, you can simply achieve this with toLocaleString()在现代浏览器中,您可以简单地使用toLocaleString()来实现

 console.log((1230000000000).toLocaleString()); console.log((12300000000).toLocaleString()); console.log((1230000.152).toLocaleString());

I know I'm very late for giving the answer, But still, I post this answer because this question is coming in the search result of How to add a dynamic comma in number in javascript , So I thought I need to add an answer which is shorter and better for upcoming developers.我知道我给出答案已经很晚了,但是,我仍然发布了这个答案,因为这个问题出现在How to add a dynamic comma in number in javascript的搜索结果中,所以我想我需要添加一个答案对于即将到来的开发人员来说更短更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM