Posted By

darkphotn on 01/13/08


Tagged


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

luman


Convert String to Number in Javascript


 / Published in: JavaScript
 

Javascript sometimes confuses strings and numbers. When this happens, you get bizarre outcomes such as "2 + 2 = 22". The following code FORCES a conversion to a number.

  1. var myval = Number(document.myform.mytext.value);
  2.  
  3. //var myval = document.myform.myval.value; myval++; myval--;

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: tpsreport on January 13, 2008

Do not use this code! This is amateur-level fail. Javascript has plenty of type-casting functions available that do this properly.

Given an input value of x, you can do the following:

parseInt(x, 10) // returns x as an integer in base 10 parseInt(x, 16) // returns x as an integer in hex parseFloat(x) // returns x as a float

See the Mozilla reference docs here: http://developer.mozilla.org/en/docs/CoreJavaScript1.5Guide:PredefinedFunctions:parseIntandparseFloat_Functions

Posted By: darkphotn on January 13, 2008

Original code modified -- the new method is based on inamorix's, and is better than the original (and also better than tps's).

tpsreport, that link is dead. Check the page.

Posted By: Jacky888 on October 12, 2018

samsung galaxy tab s2 8 0 gts28vewifi sm t713 howtoandroitroot

You need to login to post a comment.