How can I add a comma to separate each group of th

2019-06-16 07:03发布

I have a text input field for a form where users are meant to enter a number. I would like to automatically insert a comma after every third digit.

For example, entering '20' would result in '20'. Entering '100' would result in '100'. But if they were to enter '1000', a comma would be inserted between the 1 and the following 0's (e.g., 1,000). Obviously this behaviour would continue should the number reach 7 digits (e.g., 1,000,000).

Is there an easy way to do this? I'm a bit of a newb at all of this, so please answer like you're talking to a child :)

10条回答
Summer. ? 凉城
2楼-- · 2019-06-16 07:42

Another way to do it, no RegEx, just array manipulation:

function decimalMark(s) {
    for (var a = s.split("").reverse(), b = [], i = 0; i < a.length; i++) { 
        if (i && i%3 === 0)
            b.unshift(",");
        b.unshift(a[i]);
    }

    return b.join("");
}

Be sure to pass a string to the function

decimalMark("1234")
查看更多
女痞
3楼-- · 2019-06-16 07:42

Simple string solution in pure JS:

function addCommas(e) {
    var tgt = e.target, val = tgt.value.replace(/,/g, ''),
        amt = Math.ceil(val.length/3), newStr = '', x = 0; 
    while ( x <= amt ) {
        newStr += val.slice(x*3,(x+1)*3);
        newStr += ( x < amt-1 ) ? ',' : '';
        x++
    }
    tgt.value = newStr;
}
document.getElementById('test').addEventListener('change', addCommas, false);

Demo: http://jsfiddle.net/kevinvanlierde/TYyfn/141/

查看更多
Root(大扎)
4楼-- · 2019-06-16 07:45

Give this a try: it may need a little tweeking.

  1. take the function from above: function addCommas(nStr){...} and put in a js file.

  2. add a script link in the page header to jquery library with: src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"

  3. be sure your text box has a unique id. ex: id="comma_input".

  4. in the same js file add

     $(document).ready(function(){ 
         $('#comma_input').keyup(function(){
             $(this).attr('value',addCommas($(this).attr('value')));
         });
     });
    
查看更多
Emotional °昔
5楼-- · 2019-06-16 07:55

You can use standart JavaScript functions. Example here; http://jsfiddle.net/azur/jD5pa/

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <title>pure js solution</title>
        <script type='text/javascript'>
            function digitGroup(dInput) {
                var output = "";
                try {
                    dInput = dInput.replace(/[^0-9]/g, ""); // remove all chars including spaces, except digits.
                    var totalSize = dInput.length;
                    for (var i = totalSize - 1; i > -1; i--) {
                        output = dInput.charAt(i) + output;
                        var cnt = totalSize - i;
                        if (cnt % 3 === 0 && i !== 0) {
                            output = " " + output; // seperator is " "
                        }
                    }
                } catch (err)
                {
                    output = dInput; // it won't happen, but it's sweet to catch exceptions.
                }
                return output;
            }
        </script>
    </head>
    <body>
        <input type="text" value="53" onkeyup="this.value = digitGroup(this.value);">
    </body>
</html>
查看更多
神经病院院长
6楼-- · 2019-06-16 07:55
var formatNumber = function(num, type) {
    var numSplit, int, dec, type;

    num = Math.abs(num);
    num = num.toFixed(2);

    numSplit = num.split('.')

    int = numSplit[0];
    if (int.length >= 3) {
        int = int.substr(0, int.length - 3) + ',' + int.substr(int.length - 3, 3);
    }

    dec = numSplit[1];

    return (type === 'exp'? sign = '-' : '+') + ' ' + int + '.' + dec;
};
查看更多
叼着烟拽天下
7楼-- · 2019-06-16 07:57
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;
}

Pass the value of the input into function and set the input with the result returned. You can bind this to an onchange event.

Here is a working example that relies on jquery to bind the change event and set the value: http://jsfiddle.net/TYyfn/

Comma script is from: http://www.mredkj.com/javascript/nfbasic.html

查看更多
登录 后发表回答