tags:

views:

71

answers:

3

Hi,

when i try "eval" function as eval ("020 * 05 + 05") it is returning 85 instead off 105. Can someone explain me why eval function behave like this? Also suggest any to overcome this problem.

+3  A: 

Numeric constants that start with a zero (like "020") are interpreted as octal. That's true for C, C++, Java, Javascript, and most any other language with even a vague cosmetic relationship to C.

If for some reason you really, really need to use "eval()", and you've got these weird strings with bogus leading zeros on the numeric constants, you might try something like this:

var answer = eval(weirdString.replace(/\b0(\d+)\b/g, '$1'));

However I wish you would find a way around using "eval()" at all.

Pointy
+1  A: 

Javascript treats numbers beginning with 0 as octal. You can either remove the leading 0's or use parseInt(yourNumber,10) to convert to base 10.

kekekela
+1  A: 

Here is a link describing how the ParseInt function works in JavaScript and hence the reason you are getting an unexpected result.

http://www.w3schools.com/jsref/jsref_parseInt.asp

Kevin
That's useful, but the thing is if he's got those strings with complete expressions in them, parseInt() isn't going to help much by itself. This is one of those cases where I wish we could walk backwards twenty or thirty steps and find out where the OP has gone astray.
Pointy