views:

127

answers:

4

How would it be a nice way of handling this?

I already thought on removing the comma and then parsing to float.

Do you know a better/cleaner way?

Thanks

+8  A: 

Nope. Remove the comma.

Matchu
+4  A: 
parseFloat( theString.replace(/,/g,'') );
J-P
Please don't use regex. `.replace(',', '')`
Adam
He also specifically said he considered removing the comma, but is interested in other ways
Michael Mrozek
@Adam, let's say the number is 1 million, `"1,000,000"`, if you don't use a regex with the global flag, only the first comma will be replaced -> `"1000,000"`.
CMS
@Adam - J-P's solution is more dynamic in that it covers multiple commas.
patrick dw
@Michael - Depends on what the OP meant by 'removing the comma'. If OP meant that he would remove the comma from the markup completely, then it is a good alternative to keep the comma and have javascript remove it only when necessary.
patrick dw
Yes, it's annoying that you have to resort to regexp to do a simple string replace when there may be more than one occurrence of the needle, but that's wacky JavaScript for you. An alternative idiom for when the needle might contain regex-special characters and you don't want to have to worry about escaping is `s.split(needle).join(replacement)`.
bobince
@Adam There is no reason *not* to use RegEx here
Josh Stodola
Ah. Sorry, had no idea that .replace replaces only once.
Adam
A: 

You can use the string replace method, but not in a one liner as a regexp allows.

while(str.indexOf(',')!=-1)str= str.replace(',','');
parseFloat(str);

Or to make a single expression without a regexp=

return parseFloat(str.split(',').join(''));

I'd use the regexp.

kennebec
A: 

Building on the idea from @kennebec, if you want to make sure that the commas are correct, and you don't want to replace commas, you could try something like this:

function myParse(num) {
  var n2 = num.split(",")
  out = 0
  for(var i = 0; i < n2.length; i++) {
    out *= 1000;
    out += parseFloat(n2[i])
  }
  return out
}
alert(myParse("1,432,85"));
// Returns 1432085, as the comma is misplaced.

It may not be as fast, but you wanted alternatives :)

bradlis7