Javascript 在带有数字的文本框中自动添加逗号 (,)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25736940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 21:48:04  来源:igfitidea点击:

Auto add comma (,) in text-box with numbers

javascriptasp.net

提问by Tar7

My current coding adds comma (,) when there are 4 or more digits. But instead of 1101 = 1,101 my code is doing this 1101 = 110,1... I want it to format and bring the comma to the front. My javascript

当有 4 位或更多位时,我当前的编码会添加逗号 (,)。但是我的代码不是 1101 = 1,101,而是执行此操作 1101 = 110,1 ... 我希望它格式化并将逗号放在前面。我的 JavaScript

<script language="javascript" type="text/javascript">   
    function AddComma(txt) {
        if (txt.value.length % 4 == 3) {
            txt.value += ",";
        }
    }
</script>


<asp:TextBox ID="TextBox3" onkeypress="AddComma(this)" runat="server"></asp:TextBox>

How do i format so the comma is in the front 1,101 or 10,101 or 100,101.

我如何格式化以便逗号在前面 1,101 或 10,101 或 100,101。

回答by Rajeev Mehta

Try this code

试试这个代码

function Comma(Num) { //function to add commas to textboxes
        Num += '';
        Num = Num.replace(',', ''); Num = Num.replace(',', ''); Num = Num.replace(',', '');
        Num = Num.replace(',', ''); Num = Num.replace(',', ''); Num = Num.replace(',', '');
        x = Num.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1))
            x1 = x1.replace(rgx, '' + ',' + '');
        return x1 + x2;
    }


<asp:TextBox ID="TextBox3" runat="server"  onkeyup = "javascript:this.value=Comma(this.value);" />

Hope this helps you.

希望这对你有帮助。

回答by vladkras

function addComma(txt) {
    txt.value = txt.value.replace(",", "").replace(/(\d+)(\d{3})/, ",");
}

right now it supports only 3 last digits

现在它只支持最后 3 位数字

FIDDLE<--- here

小提琴<--- 这里

回答by Awtszs

It will only acceptnumeric and one dot

它只会accept数字和一dot

here is the javascript

这是javascript

<script >

            function FormatCurrency(ctrl) {
                //Check if arrow keys are pressed - we want to allow navigation around textbox using arrow keys
                if (event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40) {
                    return;
                }

                var val = ctrl.value;

                val = val.replace(/,/g, "")
                ctrl.value = "";
                val += '';
                x = val.split('.');
                x1 = x[0];
                x2 = x.length > 1 ? '.' + x[1] : '';

                var rgx = /(\d+)(\d{3})/;

                while (rgx.test(x1)) {
                    x1 = x1.replace(rgx, '' + ',' + '');
                }

                ctrl.value = x1 + x2;
            }

            function CheckNumeric() {
                return event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 46;
            }

  </script>

HTML

HTML

<input type="text" onkeypress="return CheckNumeric()" onkeyup="FormatCurrency(this)" />

DEMO JSFIDDLE

演示 JSFIDDLE

回答by RobG

There are any number of functions out there to do this, here's one that inserts a thousands separator and does toFixed as well using whatever characters you specify:

有许多函数可以做到这一点,这里有一个插入千位分隔符并使用您指定的任何字符执行 toFixed 的函数:

// Format a number n using: 
//   p decimal places (two by default)
//   ts as the thousands separator (comma by default) and
//   dp as the  decimal point (period by default).
//
//   If p < 0 or p > 20 results are implementation dependent.
function formatNumber(n, p, ts, dp) {
  var t = [];
  // Get arguments, set defaults
  if (typeof p  == 'undefined') p  = 2;
  if (typeof ts == 'undefined') ts = ',';
  if (typeof dp == 'undefined') dp = '.';

  // Get number and decimal part of n
  n = Number(n).toFixed(p).split('.');

  // Add thousands separator and decimal point (if requied):
  for (var iLen = n[0].length, i = iLen? iLen % 3 || 3 : 0, j = 0; i <= iLen; i+=3) {
    t.push(n[0].substring(j, i));
    j = i;
  }
  // Insert separators and return result
  return t.join(ts) + (n[1]? dp + n[1] : '');
}

console.log(formatNumber(1101, 0)); // 1,101

回答by Etai

Assuming you have a string representation of a number:

假设您有一个数字的字符串表示形式:

function formatNum(str){
    var ind=str.length%3;
    return str.length > 3 ? (str.slice(0,ind)+','+str.slice(ind).match(/\d{1,3}/g).join(',')) : str;
}

If it's a number, not a string, then you can use toString() to change it to a string first.

如果是数字,而不是字符串,则可以先使用 toString() 将其更改为字符串。

回答by Daemon025

You can use jquery.numberbox.js for this kind of tasks.

您可以将 jquery.numberbox.js 用于此类任务。

回答by Ankur Kumar

you may use this also.

你也可以使用这个。

<script type="text/javascript">
function addcommas(x){

var thisVal = x.value;
thisVal = thisVal.replace(/,/g, '');
var thischar = ""+thisVal;

var firstval = thischar.split(".")[0];
var secondval = thischar.split(".")[1];

if(secondval==""  || secondval==undefined){secondval = "";}
else{secondval = "."+secondval;}

var chkmod = parseInt(firstval.length)%3;
var spclcon = parseInt(firstval.length)%3;
var chkdiv= parseInt(parseInt(firstval.length)/3);

    if(firstval.length > 3)
    {
        last5 = firstval.substr(0,chkmod);

        for(i=1;i<=chkdiv;i++){
            last5+= ","+firstval.substr(chkmod,3);
            chkmod = chkmod+3;
        }

        if(spclcon==0){last5 = last5.substr(1,last5.length-1)}
         return x.value = last5+""+secondval;
    }
    else{
        return x.value = firstval+""+secondval;
    }
}


</script>

回答by richardwhitney

Here is a modification to @Engineeration's answer simply casting Num to string and doing a global replace (one time) of any existing commas:

这是对@Engineeration 答案的修改,只需将 Num 转换为字符串并对任何现有逗号进行全局替换(一次):

function Comma(Num) { 
    Num = Num.toString().replace(/,/g, '');
    x = Num.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1))
        x1 = x1.replace(rgx, '' + ',' + '');
    return x1 + x2;
}