adding numbers in Javascript

Discussions

Web tier: servlets, JSP, Web frameworks: adding numbers in Javascript

  1. adding numbers in Javascript (2 messages)

    Hi,

    i have a very stupid problem in Javascript... i just want two values from input fields to be added and be returned to the value of a label field. But instead if adding the numbers they are concatenated... Now i looked some things up on the web and i found a article that stated that the first argument's type determines the type of the result. He even gave an example how to do type casting f.e.

    var stringValue="1";
    var intValue=1;

    var resultConcatenated = stringValue + intValue; // 11
    var resultAdded = intValue + stringValue; // 2

    So i thought ... hey i got it but it fails ... they still remain concatenated... has this something to do with the fact that i am using labels ?

    any help would be welcome...

    Threaded Messages (2)

  2. adding numbers in Javascript[ Go to top ]

    Try this:

    var resultAdded = intValue + parseInt(stringValue);

    parseInt() is a pre-defined global method.

    Andy
  3. adding numbers in Javascript[ Go to top ]

    Is it simplier to do this?

    var resultAdded = intValue*1 + stringValue*1;

    Since * is the operator for number, the stringValue*1 would return the int value.