Typecasting Strings to Numbers in Javascript
Feb.11, 2008 in
Development
If you are using the values on a page (e.g. the values of form elements) directly in mathematical formulas in javascript, you can have issues with ambiguity of types. For instance:
var total = 0;
total += document.myForm.element.value; // e.g. value = 5
alert(total);
The above example can lead to a result of “05″ instead of “5″ as the browser may interpret the two values as strings. To avoid this, use the Number() function to cast the string as a number:
var total = 0;
total += Number(document.myForm.element.value);
alert(total);
You can also cast a number to a string by using the String() function. See more here.
Tags: javascript, typecasting

Leave a Reply