簡體   English   中英

在帶有數字的文本框中自動添加逗號 (,)

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

當有 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>

我如何格式化使逗號在前面 1,101 或 10,101 或 100,101。

試試這個代碼

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, '$1' + ',' + '$2');
        return x1 + x2;
    }


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

希望這對你有幫助。

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

現在它只支持最后 3 位數字

小提琴<--- 這里

它只accept數字和一個dot

這是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, '$1' + ',' + '$2');
                }

                ctrl.value = x1 + x2;
            }

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

  </script>

HTML

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

演示 JSFIDDLE

有許多函數可以做到這一點,這里有一個插入千位分隔符並使用您指定的任何字符執行 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

我為我的項目做了這個。 它還會刪除所有字母。

 $('#inputNumber').on('keydown keyup', function() { this.oldVal = this.value.replace(/\\D/g, ''); this.value = Number(this.oldVal).toLocaleString(); })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="inputNumber" type="text">

假設您有一個數字的字符串表示形式:

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

如果是數字,而不是字符串,則可以先使用 toString() 將其更改為字符串。

您可以將 jquery.numberbox.js 用於此類任務。

你也可以使用這個。

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

這是對@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, '$1' + ',' + '$2');
    return x1 + x2;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM