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]}
7 Answers
var a='1,125';
a=a.replace(/\,/g,''); // 1125, but a string, so convert it to number
a=parseInt(a,10);
Hope it helps.
-
1You should always pass the radix to
parseInt
->parseInt(a, 10)
; otherwise, the JS engine makes its best guess and would interpret01125
as base 8 and convert it to597
base 10.– nbrooksCommented Sep 24, 2012 at 6:21 -
Hi All, Actually i am using java freemaker template. there i want remove comma (,) from the number. The Code is <td>${variableMap[key]}</td>. Any other solution for this ??– SreeCommented Sep 28, 2012 at 10:33
-
@sree - your code must be replacing the template placeholder with the actual value somewhere. You can try modifying there only. Commented Sep 28, 2012 at 10:40
-
i try .35 and i get back 0. seem the number has to be a full number?– websCommented Jan 22, 2018 at 10:56
-
@user3629945
parseInt
will drop any decimal part of the input Commented Jan 22, 2018 at 12:08
var a='1,125'
a=a.replace(/\,/g,'')
a=Number(a)
-
You don't need to escape commas in regex; they're not special characters.
/,/
is sufficient. Commented May 19, 2022 at 9:02
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;
};
✨ ES2021 ✨ added replaceAll
, so no need for regular expression:
const str = '1,125,100.05';
const number = parseFloat(str.replaceAll(",", ""));
You can use Regular Expression to change as it is faster than split join
var s = '1,125';
s = s.replace(/,/g, '');
//output 1125
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).
-
The comma doesn't need to be within a character class.
/,/
is sufficient. Commented May 19, 2022 at 9:03