0

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?)

mplungjan
  • 169,008
  • 28
  • 173
  • 236
dariusz
  • 441
  • 1
  • 5
  • 17

3 Answers3

0

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')
)
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

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;
Rick
  • 1,710
  • 8
  • 17
0

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;
}
dariusz
  • 441
  • 1
  • 5
  • 17