| Refresh | Home EGTry.com

convert number to string or format number for display


commentsJavascript sourceExecution result in your current browser
auto-conversion when string is expected
   document.write(123456);
   var msg="The number is: "+23;
   document.write("<br/>"+msg);
   var str1=""+123;
   document.write("<br/> typeof(str1): "+typeof(str1));
 

explicit conversion
   var number2=123;
   var string2=String(number2);
   var string3=number2.toString();
   document.write("string2: "+typeof(string2)+" value="+string2);
   document.write("<br/>string3: "+typeof(string3)+" value="+string3);
   //the results are identical
   document.write("<br/>string2===string3?"+(string2===string3));

number base
    //base 2
    var base2=7;
    document.write(base2.toString(2));
    //base 16
    var base16=1024;
    document.write("<br/>"+base16.toString(16));

number formatting
     var pi=3.14159;
     var two=2;
     var digit5=12345;
     //do rounding
     document.write(pi.toFixed(3));
    
     //add 0 if needed
     document.write("<br/>"+two.toFixed(3));

     //display as 6 numbers
     document.write("<br/>"+digit5.toPrecision(6));
     
     //use exponential
     document.write("<br/>"+digit5.toPrecision(3));