i want to remove comma from a number (e.g change 1,125 to 1125 ) in a .tpl file.
The value comes dynamically like ${variableMap[key]}
Asked
Active
Viewed 1.2e+01k times
40

John Conde
- 217,595
- 99
- 455
- 496

Sree
- 2,792
- 8
- 25
- 33
7 Answers
85
var a='1,125';
a=a.replace(/\,/g,''); // 1125, but a string, so convert it to number
a=parseInt(a,10);
Hope it helps.

web-nomad
- 6,003
- 3
- 34
- 49
-
1You should always pass the radix to `parseInt` -> `parseInt(a, 10)`; otherwise, the JS engine makes its best guess and would interpret `01125` as base 8 and convert it to `597` base 10. – nbrooks Sep 24 '12 at 06:21
-
Hi All, Actually i am using java freemaker template. there i want remove comma (,) from the number. The Code is
${variableMap[key]} . Any other solution for this ?? – Sree Sep 28 '12 at 10:33 -
@sree - your code must be replacing the template placeholder with the actual value somewhere. You can try modifying there only. – web-nomad Sep 28 '12 at 10:40
-
i try .35 and i get back 0. seem the number has to be a full number? – webs Jan 22 '18 at 10:56
-
@user3629945 `parseInt` will drop any decimal part of the input – web-nomad Jan 22 '18 at 12:08
-
You don't need to escape commas in regex; they're not special characters. `/,/` is sufficient. – BadHorsie May 19 '22 at 09:02
21
-
You don't need to escape commas in regex; they're not special characters. `/,/` is sufficient. – BadHorsie May 19 '22 at 09:02
9
You can use the below function. This function can also handle larger numbers like 123,123,123.
function removeCommas(str) {
while (str.search(",") >= 0) {
str = (str + "").replace(',', '');
}
return str;
};

Aiden Zhao
- 564
- 5
- 24
3
✨ ES2021 ✨ added replaceAll
, so no need for regular expression:
const str = '1,125,100.05';
const number = parseFloat(str.replaceAll(",", ""));

Amir2mi
- 896
- 9
- 13
2
You can use Regular Expression to change as it is faster than split join
var s = '1,125';
s = s.replace(/,/g, '');
//output 1125

levis
- 462
- 6
- 16
0
Incoming value may not always be a string. If the incoming value is a numeric the replace method won't be available and you'll get an error. Suggest using isNaN to see if numeric, then assume string and do replacement otherwise.
if(isNaN(x)) {
x = parseInt(x.replace(/[,]/g,''));
}
(Not foolproof because 'not number' doesn't prove it is a string, but unless you're doing something very weird should be good enough). You can also add other symbols to the character group to remove other stray chars (such as currency symbols).

John Mawer
- 79
- 1
-
The comma doesn't need to be within a character class. `/,/` is sufficient. – BadHorsie May 19 '22 at 09:03