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?
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.
Fastest based on the JSPerf test above: str = num. toString();
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.
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.
The simplest option is to remove all commas: parseInt(str.replace(/,/g, ''), 10)
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
.
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