#1
  1. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Posts
    698
    Rep Power
    95

    Understanding eval()


    I am trying to understand this function and I have the following code:
    PHP Code:
    alert(temp); 
    alert(    eval((((100-temp)/3))+temp)); 
    If variable temp=1 I expect the alert to produce 34 but it shows 331 instead. It concatenates instead of evaluating.
    I tried the eval() function because
    PHP Code:
    alert(    (((100-temp)/3))+temp); 
    also produces 331 when the input is 1.
    What am I doing wrong?
    Evan
  2. #2
  3. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,056
    Rep Power
    9398
    Like with PHP, avoid using eval().

    Your problem is that temp is a string, and adding a string to a number acts as string concatenation and not numeric addition.

    Run the string through parseInt() first.
    Code:
    temp = parseInt("1");
    
    alert(    (((100-temp)/3))+temp);

IMN logo majestic logo threadwatch logo seochat tools logo