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
Number(what to convert);
Example
Let's convert the boolean true
value to a number:
Number(true);
The code execution result:
1
Example
Now let's convert the boolean
false
value:
Number(false);
The code execution result:
0
Example
Let's enter the string containing a number into a function parameter:
Number('53');
As a result of the conversion, we get a number:
53
Example
And now we added spaces to a number at the beginning and at the end of the string:
Number(' 5 ');
After executing the code, extra spaces are removed and as a result we get a number:
5
Example
Let's convert an empty string:
Number('');
The code execution result:
0
Example
Now we convert a string containing a letter and a number:
Number('a5');
After executing the code, we get
the NaN
value, which
indicates an invalid math operation:
NaN
Example
Let's swap a letter and a number in a string:
Number('5a');
The result of the code executing will remain the same:
NaN
Example
Now we will convert the string where numbers are separated by a space:
Number('5 5');
As a result of the code execution, we will see again that this math operation is invalid:
NaN
Example
Let's convert the boolean true
value enclosed in a string:
Number('true');
After executing the code,
we again get NaN
:
NaN
Example
Now we convert an empty object:
Number({});
The code execution result:
NaN
Example
Let's set an empty array as a function parameter:
Number([]);
As a result, we get the
number 0
:
0
Example
Now we add a number to an array:
Number([1]);
The array is converted to a number:
1
Example
Let's convert an array including two digits:
Number([1, 2]);
As a result, we will again be informed that this math operation is invalid:
NaN
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