3

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?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Progo
  • 3,452
  • 5
  • 27
  • 44

2 Answers2

7

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

Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61
3

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)
Cris
  • 12,799
  • 5
  • 35
  • 50