JavaScript Numbers: Number(), parseInt(), parseFloat()

FSPLFPQBCZ JavaScript’s NaN stands for ‘Not a Number’. This is used when an operation that should have returned a number has failed.

NaN used in any operation will always return NaN.

NaN is not equivalent to any value, including itself. (NaN == NaN) returns false.

You can test this value with the isNaN() function. Booleans, strings with only numbers, or numeric values will return false when passed to the isNaN() function. Strings that contain other characters besides numbers, and NaN itself, will return true when passed in. If the value can be converted to a number it will return true, otherwise, it will return false.

Objects use the valueOf() and toString() methods to determine if the returned value can be converted into a number.

The Number() casting function

Number(true);       //1
Number(false);      //0
Number(13);         //13
Number("13");       //13
var b;
Number(b);          //Number(undefined) NaN
var b=10;
Number(b);          //10
Number("1.5");      //1.5
Number("01.5");     //1.5
Number("0xA");      //10
Number("");         //0
Number("cindy");    //NaN
Number("123cindy"); //NaN
Number("123.123.123");  //NaN
Number("4.89e7");   //48900000

The parseInt() function

parseInt(true);     //NaN
parseInt(false);    //NaN
parseInt(13);       //13
parseInt("13");     //13
var k;              //k is undefined
parseInt(k);        //NaN
var b=10;
parseInt(b);        //10
parseInt("1.5")     //1
parseInt("01.5")    //1
parseInt("0xA");    //10
parseInt("");       //NaN
parseInt("cindy");  //NaN
parseInt("123cindy") //123
parseInt("123.123.123") //123
parseInt("4.89e7")  //4

parseInt() takes a second argument which will tell it to parse in a certain base system.

parseInt("10",16);  //hexadecimal 16
parseInt("10",8);   //octal 8
parseInt("10",10);  //decimal 10

The parseFloat() function

parseFloat(true);      //NaN
parseFloat(false);     //NaN
parseFloat(13);        //13
parseFloat("13");      //13
var j;                 //undefined
parseFloat(j);         //NaN
var b=10;
parseFloat(b)          //10
parseFloat("1.5")      //1.5
parseFloat("01.5")     //1.5
parseFloat("0xA")      //0  only uses decimal system
parseFloat("")         //NaN
parseFloat("cindy");   //NaN
parseFloat("123cindy") //123.123
parseFloat("4.89e7");  //48900000

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top