toFixed() returns a string, with the number written with a specified number of decimals:

var x = 9.656;
x.toFixed(0);           // returns 10
x.toFixed(2);           // returns 9.66
x.toFixed(4);           // returns 9.6560
x.toFixed(6);           // returns 9.656000

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.

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

x = true;
Number(x);        // returns 1
x = false;     
Number(x);        // returns 0
x = new Date();
Number(x);        // returns 1404568027739
x = "10"
Number(x);        // returns 10
x = "10 20"
Number(x);        // returns NaN

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

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 

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

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

Yonggoo Noh

I am interested in Computer science and Mathematics.