Converting Variables to Numbers

There are 3 JavaScript methods that can be used to convert variables to numbers:

  • The Number() method
  • The parseInt() method
  • The parseFloat() method

These methods are not number methods, but global JavaScript methods.


Global JavaScript Methods

JavaScript global methods can be used on all JavaScript data types.

These are the most relevant methods, when working with numbers:

Method Description
Number() Returns a number, converted from its argument.
parseFloat() Parses its argument and returns a floating point number
parseInt() Parses its argument and returns an integer
 

The Number() Method

Number() can be used to convert JavaScript variables to numbers:

Example

Number(true);          // returns 1
Number(false);         // returns 0
Number("10");          // returns 10
Number("  10");        // returns 10
Number("10  ");        // returns 10
Number(" 10  ");       // returns 10
Number("10.33");       // returns 10.33
Number("10,33");       // returns NaN
Number("10 33");       // returns NaN
Number("John");        // returns NaN
 

If the number cannot be converted, NaN (Not a Number) is returned.


The Number() Method Used on Dates

Number() can also convert a date to a number:

Example

Number(new Date("2017-09-30"));    // returns 1506729600000
 

The Number() method above returns the number of milliseconds since 1.1.1970.


The parseInt() Method

parseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned:

Example

parseInt("-10");        // returns -10
parseInt("-10.33");     // returns -10
parseInt("10");         // returns 10
parseInt("10.33");      // returns 10
parseInt("10 20 30");   // returns 10
parseInt("10 years");   // returns 10
parseInt("years 10");   // returns NaN 
 

If the number cannot be converted, NaN (Not a Number) is returned.


The parseFloat() Method

parseFloat() parses a string and returns a number. Spaces are allowed. Only the first number is returned:

Example

parseFloat("10");        // returns 10
parseFloat("10.33");     // returns 10.33
parseFloat("10 20 30");  // returns 10
parseFloat("10 years");  // returns 10
parseFloat("years 10");  // returns NaN
If the number cannot be converted, NaN (Not a Number) is returned.



Practice Excercise Practice now