Skip to main content

Be careful parsing formatted numbers in JavaScript

I was working on a script recently and ran into an unexpected issue. The work involved parsing a number-range string into an array of numbers, e.g. “1-100” into [1,100].

My first instinct was to reach for parseInt with something like:

"1-100".split("-").map((string) => parseInt(string));
// [1, 100]

This worked nicely until I rant into formatted numbers in the dataset: “1,000-2,000”. Instead of parsing the strings into the expected numbers, parseInt seems to treat the commas as decimals:

"1,000-2,000".split("-").map((string) => parseInt(string));
// [1, 2]

Unfortunately, parseFloat and the Number constructor similarly struggle with formatted numbers:

"1,000-2,000".split("-").map((string) => parseFloat(string));
// [1, 2]
"1,000-2,000".split("-").map((string) => Number(string));
// [NaN, NaN]

It’s interesting to me that Number returns NaN, but MDN says you probably shouldn’t be using it like this anyway.

The solution is to remove the commas before parsing. There are a few methods to do this, but String.replace will work nicely:

  .replace(",", "")
  .map((string) => parseInt(string));

If you’re curious, swapping the commas for underscores – the approved numeric separator – doesn’t work either:

// 1

There might be an optimal solution that handles numbers formatted for different locales, e.g. “1.000,00” and “1,000.00”, so please send me a message if you know of one.

Happy coding!

About the author

Sean McPherson is a software engineer for Khan Academy who specializes in web and mobile app development. He lives with his wife, sons, and dog in Pittsburgh, PA.