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