Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Commas messing with number input in Javascript

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.

like image 621
MrGlass Avatar asked Feb 14 '12 13:02

MrGlass


People also ask

How do you put a comma in input type numbers?

You can use type="text" and then add commas to the number in the onchange event.

How do you print a number with commas as thousands separators in JavaScript?

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.

How to format a number with commas in JavaScript?

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.

How do I add a comma to a string in JavaScript?

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.

How to remove comma from input value in JavaScript?

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

How to print a number with commas as thousands of separators in JavaScript?

Answer: Use RegEx with replace method. function numberWithCommas (x) { return x.toString ().replace (/\B (?= (\d {3})+ (?!\d))/g, ","); }


2 Answers

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); 
like image 93
adelphus Avatar answered Oct 11 '22 14:10

adelphus


or even better

var s="jdjsghd0182.99"; var str = parseFloat(s.replace(/[^0-9 | ^.]/g, '')); 
like image 25
Venkat Reddy Avatar answered Oct 11 '22 14:10

Venkat Reddy