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?
Asked
Active
Viewed 2.3k times
23
informatik01
- 15,636
- 10
- 72
- 102
David
- 2,694
- 6
- 24
- 30
5 Answers
46
The simplest option is to remove all commas: parseInt(str.replace(/,/g, ''), 10)
SLaks
- 837,282
- 173
- 1,862
- 1,933
11
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.
-
2`parseInt()` should be provided a radix when being called, to eliminate the hex interpretation of a number. – Nick Craver Nov 03 '10 at 00:58
8
If you only have numbers and commas:
+str.replace(',', '')
The + casts the string str into a number if it can. To make this as clear as possible, wrap it with parens:
(+str.replace(',', ''))
therefore, if you use it in a statement it is more separate visually (+ +x looks very similar to ++x):
var num = (+str1.replace(',', '')) + (+str1.replace(',', ''));
Javascript code conventions (See "Confusing Pluses and Minuses", second section from the bottom):
JustcallmeDrago
- 1,885
- 1
- 13
- 23
-
your solution will replace only the first comma, not all of them so it will not work for numbers >= 1,000,000 – daniel.sedlacek Dec 20 '16 at 11:22
2
You can do it like this:
var value = parseInt("15,678".replace(",", ""));
treeface
- 13,082
- 3
- 49
- 57
-
your solution will replace only the first comma, not all of them so it will not work for numbers >= 1,000,000 – daniel.sedlacek Dec 20 '16 at 11:24
-
@daniel.sedlacek the question was "I want to convert the string "15,678" into a value 15678". My answer solves this problem. I'm being pedantic here, of course, but technically correct ;) – treeface Dec 22 '16 at 18:59
2
Use a regex to remove the commas before parsing, like this
parseInt(str.replace(/,/g,''), 10)
//or for decimals as well:
parseFloat(str.replace(/,/g,''))
Nick Craver
- 610,884
- 134
- 1,288
- 1,151