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.
The Eval function evaluates the string expression and returns its value. For example, Eval("1 + 1") returns 2. If you pass to the Eval function a string that contains the name of a function, the Eval function returns the return value of the function.
eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension.
JavaScript eval() The eval() method evaluates or executes an argument. If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements.
Malicious code : invoking eval can crash a computer. For example: if you use eval server-side and a mischievous user decides to use an infinite loop as their username. Terribly slow : the JavaScript language is designed to use the full gamut of JavaScript types (numbers, functions, objects, etc)… Not just strings!
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. (Note the comment below noting that the hack shown above will have problems with numbers containing fractional parts.)
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.
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
Here's a cleaner, safer answer, assuming you've first ensured the expression doesn't have any illegal characters (in particular any lowercase z's) in it:
"blah blah arithmetic with leading 0's... 0012.0034 + 1200 - 05.0600*0 + 0"
.replace(/\b0+\b/g, 'z') // replace bare zeros with sentinel
.replace(/[1-9\.]0+/g, m => m.replace(/0/g, 'z')) // save these too
.replace(/0/g, '') // throw away the rest of the zeros
.replace(/z/g, '0') // turn sentinels back to zeros
HT Adam Wolf for reminding me of the term sentinel.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With