| Refresh | Home EGTry.com

convert string to number or parse string to number


commentsJavascript sourceExecution result in your current browser
implicit conversion
   var sum="110" - 10;
   document.write("type: "+typeof(sum)+", value="+sum);

explicit casting
    var input="123";
    var num=Number(input);
    document.write("type: "+typeof(num)+", value="+num);

parseInt, hexadecimal or with trailing non-digit letter
     //normal number
     var input="10";
     document.write(input+" => "+parseInt(input));
      
     //hexademical
     input="0x10";
     document.write("<br/>"+input+" => "+parseInt(input));

     //base-2 number
     input="1010";
     document.write("<br/>"+input+" => "+parseInt(input,2));
     //trailing non-digit
     input="10 me";
     document.write("<br/>"+input+" => "+parseInt(input));

     //not a number
     input="look at this: 100, ok?";
      document.write("<br/>"+input+" => "+parseInt(input));

parseFloat floating number
     var input="3.14";
     document.write("<br/>"+input+" => "+parseFloat(input));
   
     //parse floating number as integer, no rounding  
     input="3.9";
     document.write("<br/>"+input+" => "+parseInt(input));
     //with trailing letters
     input="3.14 PI";
     document.write("<br/>"+input+" => "+parseFloat(input));

     input="PI 3.14";
      document.write("<br/>"+input+" => "+parseFloat(input));