Drawbacks in converting Strings to Number in JavaScript | Part 01

Drawbacks in converting Strings to Number in JavaScript | Part 01

Numeric conversion happens in mathematical functions and expressions automatically. Converting a string to number can be approached in diverse ways. cov.png

Which should you use?

When?

Why?

Let's do some analysis:-

  • parseInt(): Most browsers have optimal response for parseInt(). Although it may be the fastest, here are some common mistakes parseInt does:

pars.png

Always use the parseInt() with a radix = parseInt(num, 10), don't use it if you don't want it to guess from characters.

pars.png

  • parseFloat(): It is good if you never handle hexadecimal numbers; For example,

parsF.png

A negative hexadecimal number in a string is a "special case" that will go crazy in your application if you are parsing it. Make sure to always check for NaN values in your app to avoid surprises. It also retains the problem as parseInt with characters in the number.

parsF.png

N/B: When using the parseFloat(), be careful with hexadecimal numbers, don't use it if you don't want it to guess from characters."

  • Bitwise not (~): The bitwise operator, inverts the bits of its operand. It can be used to convert a string to an integer only, but it's not for floating numbers. The good thing about it is that it will return "0" if a character appears.

bitN.png

N/B: Don't use the bitwise not unless you are sure your number ranges between the values of a signed 32-bit integer. Also, keep in mind that a 32-bit integer is a number in a range from −2 147 483 648 to +2 147 483 647. That means that when that range will be exceeded then that number will not be automatically converted into something with a broader range. The Bitwise not(~) should be used to ensure input doesn't have a character in it, only for integers

Hope this helps someone?

Watch out for Part 02...

Happy Coding ...