tags:

views:

105

answers:

5

Hi, 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  A: 

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

RageZ
+8  A: 

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

paxdiablo
Arf you add me by few seconds pax ;-) and you writing style is a lot better ;-)
RageZ
+3  A: 

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

rahul
that fact that quotes aren't required kind of boggles the mind.
Jimmy
A: 

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.

Sohnee
You still need to specify the base: parseInt('08', 10) or you will still evaluate octal numbers.
Hans Kesting
Thanks - I'll update the example.
Sohnee
A: 

I just test the numbers, like

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

It gives me exactly 9

Vinodkumar ChandraSekar
Although you are relying on implicit casting, which is where the danger lies. By being explicit with your types, you are much safer!
Sohnee