Parsing function returns NaN instead of zero as requested

68 Views Asked by At

I've got these functions:

const precisionRound = (number, precision = 0) => {
  const factor = 10 ** precision;
  return Math.round(number * factor) / factor;
};

const superParseFloat = (numberish, precision = 2) => {
  if (!!numberish) {
    return precisionRound(parseFloat(numberish.toString().replace(/[^0-9.-]/g, '')), precision);
  }
  return 0;
}

console.log(
  superParseFloat('www 111'),
  superParseFloat('222'),
  superParseFloat(333),

  superParseFloat(null),
  superParseFloat(undefined),
  superParseFloat('some text')
)

It should replace all non numeric characters from string with '', and only return numbers, for example:

superParseFloat('www 111') => 111
superParseFloat('222') => 222
superParseFloat(333)) => 333

For 'null', 'undefined' or for a string without numeric characters it should return 0, eg.:

superParseFloat(null) => 0
superParseFloat(undefined) => 0
superParseFloat('some text') => 0

It works fine apart from when I'm passing a string without numeric characters. Then it returns NaN, for example:

superParseFloat('some text') returns NaN

I think it's something to with putting another if statement using isNaN() for return value but I can't figure out how to use it (if i'm right in thinking at all?)

3

There are 3 best solutions below

3
mplungjan On

We can put the isNaN before the rounding

const precisionRound = (number, precision = 0) => {
  const factor = 10 ** precision;
  return Math.round(number * factor) / factor;
};

const superParseFloat = (numberish, precision = 2) => {
  if (!!numberish) {
    const replaced = parseFloat(numberish.toString().replace(/[^0-9.-]/g, ''));
    return Number.isNaN(replaced) ? 0 : precisionRound(replaced, precision);
  }
  return 0;
}

console.log(
  superParseFloat('www 111'),
  superParseFloat('222'),
  superParseFloat(333),

  superParseFloat(null),
  superParseFloat(undefined),
  superParseFloat('some text')
)

1
Rick On

the problem is parseFloat('') returns NaN

instead do this:

var formattedValue = numberish.toString().replace(/[^0-9.-]/g, '');
if (!! formattedValue) {
   return precisionRound(parseFloat(formattedValue), precision);
} else
   return 0;
0
dariusz On

OK, I think I've got it:

const superParseFloat = (numberish, precision = 2) => {
  if ( !!numberish) {
    const converted = precisionRound(parseFloat(numberish.toString().replace(/[^0-9.-]/g, '')), precision);
    if (!Number.isNaN(Number(converted))) {
      return converted;
    }
     return 0;
  }
  return 0;
}