Home >Web Front-end >JS Tutorial >Just a Number please

Just a Number please

Barbara Streisand
Barbara StreisandOriginal
2025-01-04 19:53:41472browse

Just a Number please

Number conversion: just a number please

Converting something to a Number can be a puzzling experience in ECMAScript (ES). There are edge cases with weird results. For example Number(null) or Number([]) return 0. Trying to convert a Symbol will throw a TypeError.

So here's a small utility (a factory function) to convert input to the numbers one expects. It returns NaN when conversion doesn't comply to our standards1 (so: [nr utility](null) will return NaN).

Notes:

  • most edge cases are mitigated, not all.
  • Number strings containing ',' (e.g. 0.42.toLocaleString("nl"): '0,42') will also be converted.
  • By default the function from the the factory does not include 'converting' Infinity (to ... well ... Infinity).

The embedded Stackblitz example compares the result of default (ES) conversion (Number(...)) to conversion using the utility for a number of values.

1 Which may very well not be your standards, feel free to comment or modify the function

The above is the detailed content of Just a Number please. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn