VirtualMV/JavaScript/Starting/Strings and numbers

String concatenation(js1_06)
A string is most often text, for example "Hello World!". To stick two or more string variables together (concatenate), use the + operator

Example :.

Prompting for numbers (js1_07)
(As this uses the prompt command will not work if downloaded from the Internet in IE 7+)

When you use the prompt (or input box) to get a user to submit a number of things can go wrong!

Example :.

Alternative example for IE 7+ (js1_07a)
To show how this works in IE 7 we will assign the number "10" to num1 and "25" num2

Example :.

Converting text to numbers
One of the things you need to be very careful with in JavaScript is that adding two strings together is quite different than adding two numbers. So
 * Adding "12" + "34" will give "1234" whereas
 * Adding numbers 12 + 34 gives 46

When you get user input via a textbox (notice it is called a TEXT box) numbers are captured as strings, so before you can add them they need to be converted to numbers. You can force a number conversion by simply adding a number to the text value e.g.

Or you can use number conversion functions such as;


 * parseFloat - for conversion to a floating-point number
 * The example below will give 10.33.
 * Other conversions: "12" (12), "12.00" (12), "12.25" (12.25), "31 32 33" (31), " 22" (22), "25 years" (25), "age is 25", (NaN)


 * parseInt - for string-to-integer conversion.
 * eval(string) - where the string is evaluated.

Refs: Javascript Type-Conversion (n.d.), JavaScript eval Function (Refsnes Data, 2011)

If you want to manage the number of decimal points use

Converting text to numbers (js1_08)
(Contains prompt will work in most browsers and IE 7+ offline)

To convert an input string to number we need to use parseInt or parseFloat

Example :.