Reputation: 19183
Below, I have a number which I am trying to format using javascript. But it returns NaN.
var v = "153,452.47";
alert(Math.round(v));
You can use following fiddle: Example
How can we format a numeric string having separators?
Upvotes: 0
Views: 1173
Reputation: 135287
I think this will work well
var v = "153,452.47";
var float = parseFloat(v.replace(/[^0-9.]/g, ''));
// => 153452.47
If you want to round to integer
var v = "153,452.47";
float.toFixed(0);
// => 153452
Let's make a nice little function!
var roundFormattedNumber = function(n){
var result = parseFloat(n.replace(/[^0-9.]/g, ''));
return isNaN(result) ? NaN : result.toFixed(0);
};
This works more nicely than the other solutions provided, because it's a whitelist regexp replace rather than a blacklist one. That means that it will even work for numbers like $ 1,234.56
The other solutions provided will not work for these numbers
roundFormattedNumber("$ 123,456,489.00");
//=> 123456789
roundFormattedNumber("999.99 USD");
//=> 1000
roundFormattedNumber("1 000 €");
//=> 1000
roundFormattedNumber("i like bears");
//=> NaN
Upvotes: 8
Reputation: 3932
Try This
var v = "153,452.47";
Math.round(parseFloat(v.replace(",","")));
Upvotes: 0
Reputation: 39280
You have to remove the comma.
parseFloat("153,452.57".replace(/,/g,"")).toFixed(0);
if you want 2 decimals:
parseFloat("153,452.57".replace(/,/g,"")).toFixed(2);
Upvotes: 1