/ 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.
Expand |
Embed | Plain Text
var myval = Number(document.myform.mytext.value); //var myval = document.myform.myval.value; myval++; myval--;
Comments
Subscribe to comments
You need to login to post a comment.

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 10parseInt(x, 16) // returns x as an integer in hexparseFloat(x) // returns x as a floatSee the Mozilla reference docs here: http://developer.mozilla.org/en/docs/CoreJavaScript1.5Guide:PredefinedFunctions:parseIntandparseFloat_Functions
This is a quick and dirty one-line hack that works.
A more professional method would be:
function $n (n) { return (typeof(n) == 'number') ? new Number(n) : NaN; } // originally posted by inamorix
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.