Reputation: 7
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.
Upvotes: 0
Views: 1618
Reputation: 250932
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.
Upvotes: 0
Reputation: 323
I just test the numbers, like
a= 08; b= 1; c= a+b;
It gives me exactly 9
Upvotes: 0
Reputation: 27313
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
Upvotes: 1
Reputation: 187050
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
Upvotes: 3
Reputation: 881523
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).
Upvotes: 8