3

I guess I can format it back. I'm just interested in why it's happening.

function test(d){
 console.log(d) // 151028224
}
console.log(test(00001100101000))
Boann
  • 48,794
  • 16
  • 117
  • 146
Kevin
  • 497
  • 1
  • 5
  • 13
  • 1
    See also https://stackoverflow.com/a/2803188/1563833 regarding how to write binary numbers. – Wyck Jul 24 '19 at 13:56
  • 1
    As a general rule in all programming languages: all numbers are stored in binary, and, by default, displayed as decimal. The computer does not bother to track what format was used to write the number. – Boann Jul 24 '19 at 14:24

2 Answers2

4

The function has nothing to do with it.

The JavaScript compiler converts your number literal into a Number when it compiles the source code.

Since the number starts with a 0, it is treated as octal instead of decimal.

StardustGogeta
  • 3,331
  • 2
  • 18
  • 32
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
4

By default, any number literally written with a zero at the beginning is considered as octal (base 8) number representation, and then, when you show back any number with console.log, it is written as its base 10 representation.

console.log(05)
console.log(06)
console.log(07)
console.log(010)
console.log(011)

It's recommended to avoid this in code, because it can lead to confusions :

if the number contains the digits 8 or 9, it cannot be a base-8 number, and thus treated as base 10 !

console.log(05)
console.log(06)
console.log(07)
console.log(08) // Yiiik !
console.log(09) // Yiiik !
console.log(010)
console.log(011)
Pac0
  • 21,465
  • 8
  • 65
  • 74