Using Javascript Number objects.

Using the build-in Number object.

  • You can create an object with a member variable that is a primitive datatype number with this Javascript build-in Number object.
  • You use the new keyword to create an object that contains a primitive number.
    var obj_num= new Number(7.345);
  • This Javascript build-in Number object is also a wrapper for all primitive numbers.
  • This means you can use the properties and methods contained in the Number object, not only on all new-created number objects, but also on all primitive number values.
    <script type="text/javascript">
      var prim_num = 237.67599;
       document.write("Used toFixed with 2 decimals: "+prim_num.toFixed(2)+"<br>");
       document.write("Used toFixed with 2 decimals: "+5.4789.toFixed(2)+"<br>");
  • Javascript will automatically use the valueOf() method, which exits in the Number object, when there is a need to convert a Number object value to a primitive value.
    For example:
    <script type="text/javascript">
     // First a primitive number.
     var prim_num1=7.0;
     // Here is the same, using an object.
     var obj_num1= new Number(7.0);
     document.write("Javascript uses the valueOf() method "+
                       " before comparing values<br>");
     if (prim_num1==obj_num1){
       document.write("Values are equal<br>");
  • As you probably already have seen there is no good reason to create number objects.
  • At last; You can use the Number object as a function to create primitive number.
  • Whether you create an object, or use the Number object as a function, you can convert a strings with a number to a number object or a primitive number value.
    For example:
    <script type="text/javascript">
     // Create a primitive number with the Number as function.
      var prim_num1=Number(7.0);
     // Here is the same, using a string to number convertion.
      var prim_num2= Number("7.0");
      if (prim_num1===prim_num2){
        document.write("Value and datatype are equal!<br>");
  • I example above we converts a string number to a number, but the following methods are may be more preferable:
    var num2=parseFloat("789.45"); // parse to a float number
    var num3=parseInt("789",10); // parse to an integer using base 10 (desimal) 
    var num1=+"890.5";  // you only puts a + of - sign before the string
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.