...

View Full Version : How to calculate properly?



zk0
02-15-2007, 02:55 PM
Hi,

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!

nikkiH
02-15-2007, 03: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);

zk0
02-15-2007, 04:05 PM
Thank you "nikkiH"! :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum