Forem

KooiInc
KooiInc

Posted on • Edited on

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 class free object oriented factory) to convert input to the numbers one expects. It returns NaN when conversion doesn't comply to our standards1 (so: [nr utility instance](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 way the function converts Booleans, Infinity or empty Strings can be modified (sometimes you may want to convert true to 1 etc.).

The embedded Stackblitz example compares the result of default (ES) conversion (Number(...)) to conversion using the utility for a number of values and shows the use of modifiers to change the way it converts things to Number.

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay