I have a page with some elements that are controlled by the user. One of these is a text input field, where the user is supposed to input a number. Everything works well if the user only inputs digits (EG 9000), but is the user uses comma notation (the being 9,000) javascript doesn't take the input as an integer.
How can I remove the commas and/or force the input to an integer? I tried using parseint(), but it doesn't seem to work with commas.
You can use type="text" and then add commas to the number in the onchange event.
Artturi Jalli. To comma-separate thousands in a big number in JavaScript, use the built-in toLocaleString() method. It localizes the number to follow a country-specific number formatting. To separate thousands with commas, localize the number to the USA.
The best way to format numbers in JavaScript is to use the toLocaleString () method. This method exists on the Number object and will return a string with the number formatted with commas. If you live in the US, you can pass the method a locale string of en-US to format the number with commas.
The easy ways to add commas to numbers in Javascript are: Use the toLocaleString () function. var num = 1234567.89; var commas = num.toLocaleString ("en-US"); Convert the number to a string, and use a regular expression replace.
In my view, you can use the replace () to remove the comma from your input value, and then use parseInt () to get an correct number. Like this : var num1 = document.getElementById ("firstNumber").value; num1 = parseFloat (num1);
Answer: Use RegEx with replace method. function numberWithCommas (x) { return x.toString ().replace (/\B (?= (\d {3})+ (?!\d))/g, ","); }
Use a global regular expression to replace all commas with an empty string:
var str = "12,345,678"; str = str.replace(/,/g, ""); parseInt(str, 10);
or even better
var s="jdjsghd0182.99"; var str = parseFloat(s.replace(/[^0-9 | ^.]/g, ''));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With