Shakun Chaudhary Shakun Chaudhary - 6 months ago 21
Javascript Question

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

This code is working here



function numberWithCommas(number) {
if (isNaN(number)) {
return '';
}

var asString = '' + Math.abs(number),
numberOfUpToThreeCharSubstrings = Math.ceil(asString.length / 3),
startingLength = asString.length % 3,
substrings = [],
isNegative = (number < 0),
formattedNumber,
i;

if (startingLength > 0) {
substrings.push(asString.substring(0, startingLength));
}

for (i=startingLength; i < asString.length; i += 3) {
substrings.push(asString.substr(i, 3));
}

formattedNumber = substrings.join(',');

if (isNegative) {
formattedNumber = '-' + formattedNumber;
}

document.getElementById('test').value = formattedNumber;
}

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




Answer

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() {
    return this.split("").reverse().join("");
}

function reformatText() {
    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 comma
    document.getElementById('test').value = x;
}
<input id="test" class="test" onkeyup="reformatText()">

Comments