0

I have numbers in javascript from 01(int) to 09(int) and I want add 1(int) to each one.

For example:

01 + 1 = 2
02 + 1 = 3

But

08 + 1 = 1
09 + 1 = 1

I know the solution. I've defined them as float type.

But I want to learn, what is the reason for this result?

Thank you.

1
  • Dont use twitter abbreviations here. Reformat your question. Commented Mar 5, 2010 at 9:22

5 Answers 5

8

Javascript, like other languages, may treat numbers beginning with 0 as octal. That means only the digits 0 through 7 would be valid.

What seems to be happening is that 08 and 09 are being treated as octal but, because they have invalid characters, those characters are being silently ignored. So what you're actually calculating is 0 + 1.

Alternatively, it may be that the entire 08 is being ignored and having 0 substituted for it.

The best way would be to try 028 + 1 and see if you get 3 or 1 (or possibly even 30 if the interpretation is really weird).

Sign up to request clarification or add additional context in comments.

1 Comment

Arf you add me by few seconds pax ;-) and you writing style is a lot better ;-)
3

Since you haven't specified the radix it is treated as octal numbers. 08 and 09 are not valid octal numbers.

parseInt(08,10) + 1;

will give you the correct result.

See parseInt

1 Comment

that fact that quotes aren't required kind of boggles the mind.
1

This because if your do 09 + 1 the 09 is formated as octal (because of being prefixed by 0). Octal values go to 0 to 7, your code seems to prove that certain JavaScript engine convert 8 and 9 to invalid characters and just ignore them.

Yu shouldn't prefix by 0 your numbers if you don't want to use the octal (like using the normal decimal numbers).

See this page for reference and wikipedia for what is the octal

Comments

0

I just test the numbers, like

a= 08; b= 1; c= a+b;

It gives me exactly 9

Comments

0

As you may have seen from the answers above, you are having type-conflict. However, I thought I would also suggest the correct solution to your problem...

So as we know, 08 and 09 are treated as ocal in this example:

08 + 1 = 1
09 + 1 = 1

So you need to specify what they actually are:

parseInt("08", 10) + 1 = 1
parseInt("09", 10) + 1 = 1

Don't define them as a float if you want them to be integers.

1 Comment

You still need to specify the base: parseInt('08', 10) or you will still evaluate octal numbers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.