Javascript number object example

Javascript number object:

The JavaScript Number object represents numerical data which can be integers or floating-point numbers.

How to create javascript number object:

1. By using number literals.
2. By using Number() constructor.

By using number literals:

When we create a number literal browser automatically converts it to Number object.

Syntax:

var num1 = value;

Example:

<html>
<body>
<script> 
function stuClassName(className){  
this.className=className;     
}  
function Student(name,rollNo){  
this.name=name;  
this.rollNo=rollNo; 
this.stuClassName= stuClassName;  
}  
var student=new Student("Jai", "MCA/07/06"); 
student.stuClassName("MCA Final");
document.write("Name: " +student.name + "</br>");  
document.write("RollNo: " + student.rollNo + "</br>");  
document.write("Class: " + student.className);      
</script>  
</body>
</html>

Try it:

JS Bin on jsbin.com
 

By using Number() constructor:

We can create a JavaScript Number object by using Number() constructor. It returns NaN if value is not a number.

Syntax:

var num1 = new Number(value);

Example:

<!DOCTYPE html>
<html>
<body>
<script>
var num1=new Number(102);//Enteger value  
var num2=Number(102.7);//Floating point value  
var num3=Number(13e4);//Exponent value
document.write("Integer Value: "+num1 + "</br>");
document.write("Floating point Value: "+num2 + "</br>");
document.write("Exponent Value: "+num3);
</script>
</body>
</html>

Try it:

JS Bin on jsbin.com
 

JavaScript number constants/properties:

Property Description
MAX_VALUE It specify the largest possible value.
MIN_VALUE It specify the smallest possible value.
NaN Equal to a value that is not a number.
NEGATIVE_INFINITY A value that is less than MIN_VALUE.
POSITIVE_INFINITY A value that is greater than MAX_VALUE

 

JavaScript number methods:

Methods Description
toExponential(fractionDigits) It returns a string representing the number object in exponential notation.
toFixed(digits) It limits the number of digits after decimal value.
toPrecision(digits) It formats the number with given number of digits.
toString() It converts number into string.
valueOf() It converts other type of value into number.