41

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]}

0

7 Answers 7

86
var a='1,125';
a=a.replace(/\,/g,''); // 1125, but a string, so convert it to number
a=parseInt(a,10);

Hope it helps.

6
  • 1
    You 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
    Commented 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 ??
    – Sree
    Commented 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.
    – web-nomad
    Commented Sep 28, 2012 at 10:40
  • i try .35 and i get back 0. seem the number has to be a full number?
    – webs
    Commented Jan 22, 2018 at 10:56
  • @user3629945 parseInt will drop any decimal part of the input
    – web-nomad
    Commented Jan 22, 2018 at 12:08
22
var a='1,125'
a=a.replace(/\,/g,'')
a=Number(a)
1
  • You don't need to escape commas in regex; they're not special characters. /,/ is sufficient.
    – BadHorsie
    Commented May 19, 2022 at 9: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;
};
7
var s = '1,125';
s = s.split(',').join('');

Hope that helps.

5

✨ ES2021 ✨ added replaceAll, so no need for regular expression:

const str = '1,125,100.05';
const number = parseFloat(str.replaceAll(",", ""));
0
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
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).

1
  • The comma doesn't need to be within a character class. /,/ is sufficient.
    – BadHorsie
    Commented May 19, 2022 at 9:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.