Saturday, 25 January 2014

Number Object

·         JavaScript has only one type of number.
·         Numbers can be written with, or without decimals.
·          
Example
·         var pi=3.14;    // A number written with decimals
var x=34;       // A number written without decimals
Extra large or extra small numbers can be written with scientific (exponent) notation:
Example
var y=123e5;    // 12300000
var z=123e-5;   // 0.00123

Number Properties
  • MAX_VALUE
  • MIN_VALUE
  • NEGATIVE_INFINITY
  • POSITIVE_INFINITY
  • NaN
  • prototype
  • constructor
All number properties are properties of JavaScripts' number object wrapper called Number.
These properties can only be accesses as Number.MAX_VALUE.
Using num.MAX_VALUE, where num is a created object or a primitive number value, will return undefined.


Number Methods
  • toExponential()
  • toFixed()
  • toPrecision()
  • toString()
  • valueOf()
Note: Primitive values, like 3.14, cannot have properties and methods (because they are not objects).
With JavaScript, all methods of the number object are also available to primitive values, because Javascript will temporarily transfer primitive values to objects before executing the methods.


Numbers Can be Numbers or Objects

JavaScript numbers can be primitive values created from literals, like var x = 123;
JavaScript number can also be objects created with the new keyword, like var y = new Number(123);

Example

var x = 123;
var y = new Number(123);
typeof(x) // returns Number
typeof(y) // returns Object
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>

<script>
var x = 123;              // x is a number
var y = new Number(123);  // y is an object
var txt = typeof(x) + " " + typeof(y);
document.getElementById("demo").innerHTML=txt;
</script>

</body>


</html>
Normally, because of some nasty side effects, you will not define numbers as objects.

Example

var x = 123;              
var y = new Number(123);
(x === y) // is false because x is a number and y is an object.



Ex:
<!Number object>
<html>
<body>

<script>

var x;
document.write("<p>Only 17 digits: ");
x=12345678901234567890;
document.write(x + "</p>");

document.write("<p>0.2 + 0.1 = ");
x=0.2+0.1;
document.write(x + "</p>");

document.write("<p>It helps multiplying and dividing by 10: ");
x=(0.2*10+0.1*10)/10;
document.write(x +"</p>");

</script>

</body>

<!-- http://improvejavascript.blogspot.in/ -->
</html>

Ex:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>

<script>
var x = 123;              // x is a number
var y = new Number(123);  // y is an object
var txt = typeof(x) + " " + typeof(y);
document.getElementById("demo").innerHTML=txt;
</script>

</body>


</html>

Ex3:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>

<script>
var x = 123;              // x is a number
var y = new Number(123);  // y is an object
document.getElementById("demo").innerHTML = x===y;
</script>

</body>


</html>

No comments:

Post a Comment