admin管理员组

文章数量:1335411

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.

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.

Share Improve this question edited Mar 5, 2010 at 9:27 paxdiablo 883k241 gold badges1.6k silver badges2k bronze badges asked Mar 5, 2010 at 9:21 yasinkyasink 73 bronze badges 1
  • Dont use twitter abbreviations here. Reformat your question. – N 1.1 Commented Mar 5, 2010 at 9:22
Add a ment  | 

5 Answers 5

Reset to default 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).

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

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

I just test the numbers, like

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

It gives me exactly 9

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.

本文标签: Javascript int numbers addition problemStack Overflow