Miral
Miral

Reputation: 6038

eval creating problems in evaluating

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??

Upvotes: 1

Views: 493

Answers (3)

Gumbo
Gumbo

Reputation: 655229

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")

Upvotes: 1

SLaks
SLaks

Reputation: 887395

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.

Upvotes: 8

Victor Nicollet
Victor Nicollet

Reputation: 24577

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.

Upvotes: 1

Related Questions