0

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?

SharpCoder
  • 18,279
  • 43
  • 153
  • 249

3 Answers3

8

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
Mulan
  • 129,518
  • 31
  • 228
  • 259
  • "This works more nicely than the other solutions provided" That depends; if you want to fail fast on rubbish data you should throw an error so you know where exactly the application is failing. Accepting there might be a comma in the string is different than excepting any string with numbers in it. None of the examples check for NaN though (your function will return when no numbers are in the string) but it would be wise to do so before processing the data further. +1 for a nice complete answer – HMR Jun 26 '13 at 07:44
  • @HMR, I've added an explicit NaN return. Thanks for the feedback. – Mulan Jun 26 '13 at 15:25
1

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);
jcsanyi
  • 8,133
  • 2
  • 29
  • 52
HMR
  • 37,593
  • 24
  • 91
  • 160
0

Try This

var v = "153,452.47";
Math.round(parseFloat(v.replace(",","")));
Dev
  • 3,922
  • 3
  • 24
  • 44