Skip to content Skip to sidebar Skip to footer

Formatting Number As Thousand Using Only Javascript

Console.log is showing the correct result, but how can I add the same formatting to the input type while typing. Input type is reset after every comma to zero. 1000 to 1,000 Please

Solution 1:

Some notes:

  • Because you want commas, the type is not a number, it's a string
  • Because you want to work on the input after you type, it's onkeyup not onkeypressed

I have a solution that does a regex replace for 3 characters with 3 characters PLUS a comma:

var x = "1234567";
x.replace(/.../g, function(e) { return e + ","; } );
// Gives: 123,456,7

i.e. almost the right answer, but the commas aren't in the right spot. So let's fix it up with a String.prototype.reverse() function:

String.prototype.reverse = function() {
    returnthis.split("").reverse().join("");
}

functionreformatText() {
    var x = document.getElementById('test').value;
    x = x.replace(/,/g, ""); // Strip out all commas
    x = x.reverse();
    x = x.replace(/.../g, function(e) { return e + ","; } ); // Insert new commas
    x = x.reverse();
    x = x.replace(/^,/, ""); // Remove leading commadocument.getElementById('test').value = x;
}
<inputid="test"class="test"onkeyup="reformatText()">

Solution 2:

functionnumberWithCommas(x) {
    var real_num =  x.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
    console.log(real_num);
    document.getElementById('test').value = real_num;
}

<input type="number" id="test" onkeypress="numberWithCommas(this.value)">

Solution 3:

Check out my fiddle here http://jsfiddle.net/6cqn3uLf/ You'd need another regex to limit to numbers but this will format based on the user's locale - which may be advantageous here.

<inputid="mytext"type="text">
$(function () {
    $('#btnformat').on('input propertychange paste', function () {
        var x = $('#btnformat').val();
 $('#btnformat').val(Number(x.replace(/,/g,'')).toLocaleString());
    });
});

Solution 4:

if jquery is not overhead for your application then you can use https://code.google.com/p/jquery-numberformatter/

Post a Comment for "Formatting Number As Thousand Using Only Javascript"