views:

53

answers:

3

i am using eval to convert string decimals to decimals.

eval("000451.01");

When i am using the above statement javascript it throws exception 'expected ;'

and when using eval("000451"); it gives me a different result.

anyone has got any idea??

+1  A: 

Numbers starting with a zero are interpreted as octal numbers. But octal numbers are only integers and not floating point numbers. So try this:

eval("451.01")

But it would be better if you use the parseFloat function:

parseFloat("000451.01")
Gumbo
`parseFloat` doesn't take a base parameter.
SLaks
@SLaks: Whoops, you’re right.
Gumbo
+1  A: 

In Javascript, a token starting with zero is an integer literal in base 8. 000451 in base 8 is 297 in base 10, and 000451.01 is parsed as int(297) dot int(1) instead of a single number literal.

Remove the initial zeros and it should work.

Victor Nicollet
+7  A: 

You should not use eval to parse numbers; it will be orders of magnitude slower than normal methods.

Instead, you should use the parseFloat function. like this: parseFloat("000451.01").

The reason you're getting the error is that Javascript treats numbers that begin with 0 as octal numbers, which cannot have decimals.

If you want to parse an integer, call parseInt, and make sure to give a second parameter of 10 to force it to parse base 10 numbers, or you'll get the same problem.

SLaks