String to Number in JavaScript

There are several ways you can convert JavaScript String to Number. The best way is to make use of the unary plus `+` operator or the Number global function. You can also make use of the `parseint` or `parsefloat` functions. The following examples show how to make use of these functions.

Unary plus (+)

The Unary plus (+) operator converts all string representations of numbers, Boolean values(true and false), and null to numbers. If the operand cannot be converted into a number, the unary plus operator will return NaN

The following are some of the examples

1. Tries to convert any string to a number
2. It converts empty string / `Null` to 0
3. `True` is 1 and `False` is 0
4. Converts Octal/Hex numbers to decimal.
5. Works correctly on scientific notation numbers.
6. In case it fails to convert, then returns `NaN`

Parseint

The `parseint` function parses an string and returns an integer. The syntax of the `parseInt` is as follows. If you do not provide the `radix` then it assumes the Hexadecimal number.

`parseInt(string, radix)`

1. Tries to convert any string to a integer and not to floating number
2. Converts empty strings, null, infinity, True & false to a `NaN`
3. If the string begins with `0x` then it treats it a Hexadecimal number.
4. It does not recognize the octal number that begins with `0o`
5. The older browsers will treat the number starting with `0` as Octal.
6. Ignores the Leading & trailing spaces
7. If only the initial part of the string is a number, then it converts into number and ignores the rest.

You can make use of the `radix`. The `radix` can be from 2 to 36. Use `2` for binary, `8` for octal, `10` for decimal & `16` for HexaDecimal number.

Parsefloat

`ParseFloat` is another way to convert string to a number.

1. Tries to convert any string to a decimal or an integer number
2. Converts empty strings, null, True & false to a `NaN`
3. Returns infinity as it is.
4. It the string begins with 0x or 0o it returns zero. Does not recognize Hexa decimal or octal numbers
5. Ignores the Leading & trailing spaces
6. If only the initial part of the string is a number, then it converts into number and ignores the rest.

Number global function

You can also use the `Number` global function. It is very similar to unary plus (`+`)

1. Tries to convert any string to a number
2. It converts empty string / `Null` to 0
3. `True` is 1 and `False` is 0
4. Converts Octal/Hex numbers to decimal.
5. Works correctly on scientific notation numbers.
6. In case it fails to convert, then returns `NaN`

Check for NaN

The string to number operation may result in a `NaN`. The `NaN` stands for not a number. It is the result of numerical operations, where the result is not a number. Hence always check if the value is `NaN` using the `isNaN` method after the conversion.

References

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top