View Full Version : How to calculate properly?

Feb 15th, 2007, 01:55 PM

Can someone explain to me how I should code to calculate this?

I want to let the user add 4 different numbers (this is done) and then I want to + these numbers with each other.

This is the code I got:
var medel = tal1+tal2+tal3+tal4 ;

Let say the user enters 1+2+3+4. Then the result should be 10. But I get this number as result: 1234

What have I done wrong?

Thanks for any help!

Feb 15th, 2007, 02:25 PM
String operator + concatenates the strings.
You forgot to cast them to a number. In javascript, you can use parseInt(), parseFloat(), or Number() functions. If your input comes from the user, you should also check for NaN (not a number) using the isNaN function.

One of several ways to do this:

var medel = parseInt(tal1,10)+parseInt(tal2,10)+parseInt(tal3,10)+parseInt(tal4 ,10);

Feb 15th, 2007, 03:05 PM
Thank you "nikkiH"! :)