Convert a String to a Number
By Stephen Bucaro
Would you believe me if I told you 2 + 2 = 22? Of course not, but I can prove it with the
var c = "2" + 2;
When executed, this code will write "22". The cause of the error is that the code is trying
you know what you're doing, and your intent is to convert the numerical value to a character and
append it to the character string "2". You say "nobody would be that stupid"?
If you received the first value from a webpage form, you could very easily forget that forms
return character strings, not numerical values, and use the value in a mathematical operation.
the statements will produce the correct result, 4.
var c = parseInt("2") + 2;
to floating point numbers. With the parseFloat functions, the statements below produces
the numerical value 2. Without the parseFloat functions, it would produce the string value
var c = parseFloat("1.095") + parseFloat("0.905");
The statement shown below should produces the numerical value 200, but instead it produces
the numerical value 101. Can you find the problem?
var c = parseInt("1O0") + parseInt("100");
Somebody inadvertently typed a character O instead of a digit 0 in the first number. You
function to help you catch this error. below is an example use of the isNaN function.
var a = "1O0";
var b = "100";
if(isNaN(a) || isNaN(b))
alert("You entered a bad number");
document.write(parseInt(a) + parseInt(b));
In a situations where you need to convert a value stored as a string, for example
a value returned from a form element, to a number for use in a calculation, use the
Java Script parseInt or parseFloat function.
More Java Script Code:
• Java Script Data Types
• The Screen Object
• Convert a Number to a String
• Java Script alert Message Box
• Determine Minimum and Maximum
• Define Lines in a String
• Include a Quote Character in a String
• The break Statement