Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript / jQuery what is the best way to convert a number with a comma into an integer?

Tags:

I want to convert the string "15,678" into a value 15678. Methods parseInt() and parseFloat() are both returning 15 for "15,678." Is there an easy way to do this?

like image 208
David Avatar asked Nov 03 '10 00:11

David


People also ask

How do you convert a number to an integer in JavaScript?

In JavaScript parseInt() function (or a method) is used to convert the passed in string parameter or value to an integer value itself. This function returns an integer of base which is specified in second argument of parseInt() function.

What is the fastest way to convert number to string in JavaScript?

Fastest based on the JSPerf test above: str = num. toString();

How do you convert a string to a comma with numbers?

To parse a string with commas to a number: Use the replace() method to remove all the commas from the string. The replace method will return a new string containing no commas. Convert the string to a number.

What method convert the input into numeric value in JavaScript?

Converting Variables to Numbers There are 3 JavaScript methods that can be used to convert variables to numbers: The Number() method. The parseInt() method. The parseFloat() method.


2 Answers

The simplest option is to remove all commas: parseInt(str.replace(/,/g, ''), 10)

like image 188
SLaks Avatar answered Dec 27 '22 09:12

SLaks


One way is to remove all the commas with:

strnum = strnum.replace(/\,/g, ''); 

and then pass that to parseInt:

var num = parseInt(strnum.replace(/\,/g, ''), 10); 

But you need to be careful here. The use of commas as thousands separators is a cultural thing. In some areas, the number 1,234,567.89 would be written 1.234.567,89.

like image 33
paxdiablo Avatar answered Dec 27 '22 07:12

paxdiablo