Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    zk0
    zk0 is offline
    New Coder
    Join Date
    Dec 2006
    Posts
    51
    Thanks
    0
    Thanked 0 Times in 0 Posts

    How to calculate properly?

    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:
    Code:
    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!

  • #2
    Senior Coder nikkiH's Avatar
    Join Date
    Jun 2005
    Location
    Near Chicago, IL, USA
    Posts
    1,973
    Thanks
    1
    Thanked 32 Times in 31 Posts
    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);

    If this post contains any code, I may or may not have tested it. It's probably just example code, so no getting knickers in a bunch over a typo, OK? If it doesn't have basic error checking in it, such as object detection or checking if objects are null before using them, put that in there. I'm giving examples, not typing up your whole app for you. You run code at your own risk.
    Bored? Visit
    http://www.kaelisspace.com/

  • #3
    zk0
    zk0 is offline
    New Coder
    Join Date
    Dec 2006
    Posts
    51
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thank you "nikkiH"!


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •