Javascript Numbers

Numbers or integers are whole numbers or fractional numbers. Numbers can be added, subtracted, multiplied and divided, thus perform all arithmetic operations.

typeof operator can check datatype of numbers.


 var a=3;    	    // number; 
 var b=3.6;         // number with decimal; 
 var c=0xa;         // number in hexadecimal 
 var d=010;         // number in octal
 var e=0b100;       // number in binary
 var f=NaN;         // not a number
 var g=Infinity;    // number more than 10308
 


Methods of Numbers

MethoduseExample
toString()convert number to string.var x=6;
x.toString()="6";
toLocalString()convert number to local string.var x=6;
x.toLocalString()="6";
toExponential()convert decimal to exponential notation.var x=6;
x.toExponential()="6e+0";
toPrecision(1)convert number to Precise .var x=1.23456;
x.toPrecision(1)="1";
toPrecision(2)convert decimal to exponential notation.var x=1.23456;
x.toPrecision(2)="1.2";
toPrecision(3)convert decimal to exponential notation.var x=1.23456;
x.toPrecision(3)="1.23";

String to Number conversion

Javascript variables can be strings or numbers. Like var x="5" is string, but var y=5 is number. But both can be used in arithmetic operations. Except addition, all arithmetic operations are possible with x and y.


	var x="5";		// string
	var y=5;		// number
	
	x+x="55";		// concat
	y+y=10;			// addition
	x+y="55"		// concat, as x is string
	
	x-x=0;			// subtraction
	y-y=0;			// subtraction
	x-y=0;			// subtraction
	
	x*x=25;			// multiplication
	y*y=25;			// multiplication
	x*y=25;			// multiplication
	
	x/x=1;			// division
	y/y=1;			// division
	x/y=1;			// division
	
	x%x=0;			// modulus
	y%y=0;			// modulus
	x%y=0;			// modulus
	

Three functions to convert string to number.

  • Number()
  • parseInt()
  • parseFloat()

Number Function

Number Function can convert string to numbers.


    var a="100";
    var b="100.5";
    var c="100px";
    var d="abc100";
    
    Number(a)       //100
    Number(b)       //100.5
    Number(c)       //NaN - Not a Number
    Number(d)       //NaN - Not a Number
    

parseInt Function

parseInt Function can convert string to numbers, but non floating values only.


    var a="100";
    var b="100.5";
    var c="100px";
    var d="abc100";
    
    parseInt(a)       //100
    parseInt(a,2)     //4, binary number
    parseInt(a,8)     //64, octal number
    parseInt(a,16)    //256, hexadecimal number
    parseInt(b)       //100
    parseInt(c)       //100
    parseInt(d)       //NaN - Not a Number
    

parseFloat Function

parseFloat Function can convert string to numbers, floating and non floating both.


    var a="100";
    var b="100.5";
    var c="100px";
    var d="100.5px";
    var e="abc100";
    
    parseFloat(a)       //100
    parseFloat(b)       //100.5
    parseFloat(c)       //100
    parseFloat(d)       //100.5
    parseFloat(e)       //NaN - Not a Number
    

"+" operator and "concat()" method, both concat strings in javascript.