In most cases, Number(string)
produces better results than parseFloat(string)
:
Number.parseFloat("420") // 420
Number.parseFloat("-420") // -420
Number.parseFloat("420.69") // 420.69
Number.parseFloat("420,69") // 420 (NaN would have been better)
Number.parseFloat("420n") // 420 (NaN would have been better)
Number.parseFloat("420_69") // 420 (NaN or 42069 would have been better)
Number.parseFloat("0b1000101") // 0 (NaN or 69 would have been better)
Number.parseFloat("0x45") // 0 (NaN or 69 would have been better)
Number.parseFloat("") // NaN
Number.parseFloat(" \n") // NaN
Number("420") // 420
Number("-420") // -420
Number("420.69") // 420.69
Number("420,69") // NaN
Number("420n") // NaN
Number("420_69") // 42069
Number("0b1000101") // 69
Number("0x45") // 69
Number("") // 0 (NaN would have been better)
Number(" \n") // 0 (NaN would have been better)
If you want to protect against those last two cases, it's a lot easier to do it with Number()
than parseFloat()
:
function safeParseFloat(input: string) {
if (input.trim() === "") {
return Number.NaN
}
return Number(input)
}
parseFloat(input)
Number.parseFloat(input)
N/A
Here is a starting place for an eslint rule: https://astexplorer.net/#/gist/1569a1b6990fa03c94c76393b2ccc6a3/5e9b8eae2e48277a76e6f3680d1001b13e1d22c3
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too