Number function

The Number function converts a passed value to a number. In the case of a string, whitespace characters are cut off at the edges, then, if the string can be converted to a number, then this number is returned, and if not, it returns NaN. A true value is converted to the number 1, a false value - to the number 0. Objects during numerical conversions turn into NaN.

Syntax

javascriptNumber(what to convert);

Example

Let's convert the boolean true value to a number:

javascriptNumber(true);

The code execution result:

javascript1

Example

Now let's convert the boolean false value:

javascriptNumber(false);

The code execution result:

javascript0

Example

Let's enter the string containing a number into a function parameter:

javascriptNumber('53');

As a result of the conversion, we get a number:

javascript53

Example

And now we added spaces to a number at the beginning and at the end of the string:

javascriptNumber(' 5 ');

After executing the code, extra spaces are removed and as a result we get a number:

javascript5

Example

Let's convert an empty string:

javascriptNumber('');

The code execution result:

javascript0

Example

Now we convert a string containing a letter and a number:

javascriptNumber('a5');

After executing the code, we get the NaN value, which indicates an invalid math operation:

javascriptNaN

Example

Let's swap a letter and a number in a string:

javascriptNumber('5a');

The result of the code executing will remain the same:

javascriptNaN

Example

Now we will convert the string where numbers are separated by a space:

javascriptNumber('5 5');

As a result of the code execution, we will see again that this math operation is invalid:

javascriptNaN

Example

Let's convert the boolean true value enclosed in a string:

javascriptNumber('true');

After executing the code, we again get NaN:

javascriptNaN

Example

Now we convert an empty object:

javascriptNumber({});

The code execution result:

javascriptNaN

Example

Let's set an empty array as a function parameter:

javascriptNumber([]);

As a result, we get the number 0:

javascript0

Example

Now we add a number to an array:

javascriptNumber([1]);

The array is converted to a number:

javascript1

Example

Let's convert an array including two digits:

javascriptNumber([1, 2]);

As a result, we will again be informed that this math operation is invalid:

javascriptNaN

See also

  • the Number function
    that converts to a number
  • the parseInt function
    that extracts an integer from the beginning of a string
  • the parseFloat function
    that extracts a fractional number from the beginning of a string
  • the String function
    that converts to a string
  • the Boolean function
    that converts to a boolean value