5 ways to convert strings to numbers in JavaScript

Tram Ho

Convert from `string` to `số` , this you have done many times, right? There are quite a few ways to convert such as:

• parseInt (x)
• parseFloat (x)
• Number (x)
• + x
• ~~ x

You may be familiar with `parseInt` , `parseFloat` , `Number` and their names clearly show what they do. The `unary plus` and `Bitwise NOT` (double tilde `~~` ) are rarely used by us.

Let’s find out about the difference when `convert` strings into numbers of 5 ways above

1. Type of the conversion

Convert type

The most obvious difference is the type of result returned by each way. `parseInt` will always convert to an `Integer` .

Using `~~` will always return an `Integer`

`parseFloat` , `+` and the `Number` function will return `Integer` if possible, and will return `Float` in the remaining cases.

2. Type of the operand

All of the above can accept a string as input. But what if its input is not a string?

`parseInt` and `parseFloat` will always return `NaN` for any non- `string` input

`Number` , `+` and `~~` can `convert` `boolean` values, return 1 if input is `true` , 0 if input is `false`

and they will return `0` for `null`

When the input value is `undefined` , `Number` and `+` will return `NaN` and `~~` will describe 0

3. Invalid conversions

When the input data is incorrect (wrong format), we will see more than the difference between the above.

parseInt and parseFloat will convert as much as possible, until they find an unverified element.

`Number` and `+` will return `NaN` if the input cannot be converted. As always, `~~` returns an integer – `0` .

The way each operation deals with an empty string is also interesting. All return 0 except parseInt and parseFloat return NaN. It is interesting to convert an empty string. `parseInt` and `parseFloat` will return `NaN` and the rest will return 0

4. Exponents, hex and other bases

`parseInt` has a nice feature, when you can pass more parameters to the `hệ` (base) as the second argument. The default is base 10

As for `Number` , `+` and `~~` : it doesn’t work

On the other hand, `parseInt` cannot convert strings with exponential notation, while all other ways are possible. More precisely, `parseInt` will stop at a character that is not the first number, returning unexpected results:

Unlike the exponent, `parseInt` works correctly with base-8 system:

summary

Share the news now

Source : Viblo