I have encountered a very weird issue with my JavaScript program. I have fount that JavaScript for some reason changes 040000
into 16384
! [Example] Does anyone know why JavaScript is doing this?

- 233,700
- 52
- 457
- 497

- 3,452
- 5
- 27
- 44
-
If you really need to have a number pre-padded with zeros, try using strings. – Nobel Chicken Jun 16 '14 at 03:23
2 Answers
It's because in js, number literals prepended with 0
are considered octal (base 8)
For example
010 == 8
In your example 040000
is really 4*8*8*8*8 = 16384
because in octal each 0
in the right multiplies the value by 8.
EDIT: Bonus:
If the leading 0 is in a string representation, (for example, if it was introduced by the user), and you want to avoid converting to octal, specify the base (aka radix) with value 10
in the parseInt
method call, like this
var number = parseInt("040000", 10); //number will be 40000 ;)
In recent browsers, the radix is 10 by default, but not in old browsers, so if you want maximum compatibility also, always specify the radix parameter (usually 10).
Cheers

- 18,204
- 2
- 42
- 61
-
-
Why octal? Wouldn't `base4` or `base2 (binary)` be more realistic? Is there any way I can avoid this? – Progo Jan 10 '14 at 04:24
-
@Progo: why do you have a leading `0` in the first place? Is it from user input, or from server-side variables? – Qantas 94 Heavy Jan 10 '14 at 04:29
-
If your value is originally a string, you can use `parseInt('040000', 10)`. If it is 040000 as an integer, it is not 40000, it is 16384. The leading zero is just octal notation. – Scopey Jan 10 '14 at 04:32
-
@Scopey, I added just that at the same time as your comment xD. That's right :) – Edgar Villegas Alvarado Jan 10 '14 at 04:34
-
@Progo, see the solution to that problem in my edition – Edgar Villegas Alvarado Jan 10 '14 at 04:34
-
@EdgarVillegasAlvarado - `parseInt('040000', 10)` will return 40000 not 16384! (Atleast for me in the latest version of Chrome. - You made me check) – Scopey Jan 10 '14 at 04:38
-
@Scopey omg, of course scopey, that's obvious. editing, My bad, sorry xD – Edgar Villegas Alvarado Jan 10 '14 at 04:46
Because javascript thinks its in OCTAL
format
Explanation:-
Javascript
(like most programming languages) allows us to work directly with both octal
and hexadecimal
numbers, all we need is a way to tell which number base we are using when we specify a number. To identify octal
and hexadecimal
numbers we add something to the front of numbers using those bases to indicate which base we are using. A leading 0
on the front of a number indicates that the number following is octal while a leading 0x
indicates a hexadecimal number. The decimal number 18
can therefore also be represented as 022
(in octal
) and 0x12
(in hexadecimal
). We don't put a special symbol on the front of decimal numbers so any number that doesn't start with 0
or 0x
is assumed to be decimal.
So its same in your case
040000(base8)=16384(base10)

- 12,799
- 5
- 35
- 50