1

So I saw this strange scenario. I wanted to convert a number to a String in Node.js and I got the following.

01010100132.toString()

Turns into

"136347738"

Can someone explain this to me?

Anders
  • 9,988
  • 7
  • 30
  • 36
  • 1
    See http://stackoverflow.com/questions/11483216/why-are-leading-zeroes-used-to-represent-octal-numbers – haim770 Dec 30 '14 at 09:08

1 Answers1

3

Any numeric constant prefixed with a 0 is an octal literal (assuming all its digits are valid octal digits).

var i = 010; // 8 decimal
user229044
  • 232,980
  • 40
  • 330
  • 338
  • 01010100133.toString() gives 136347739. I thought octal didn't contain 8 or 9. – Anders Dec 30 '14 at 09:09
  • @Anders `01010100133` is octal. `136347739` is decimal. – MiKo Dec 30 '14 at 09:10
  • `136347739` is no longer octal. `136347739` is the **decimal** representation of the octal number `01010100133`. If I enter the octal literal `011`, that's decimal `9`, and that is what JavaScript will print when I output that value. – user229044 Dec 30 '14 at 09:10
  • Why dose it convert it to decimal is maybe my question then. – Anders Dec 30 '14 at 09:11
  • I think that's because the radix is not specified and by default is decimal. If you do 01010100132.toString(8) should make it octal – Jayvee Dec 30 '14 at 09:17
  • 1
    @Anders It doesn't. It converts it to a number. JavaScript (and virtually every other language) happen to be bias in that they *output* numbers in base 10 by default. Internally it's just a number, physically stored in binary, but it has no "base". It's just a number and numbers have no bases until you need to write them down or output them to the screen. – user229044 Dec 30 '14 at 09:18
  • @meagar thanks for great input and taking your time. I will try and do a better job searching for answers the next time but some topics are hard to google if you dont know what is causing it =) – Anders Dec 30 '14 at 19:50
  • @Anders There's no harm in asking, and in many cases it's difficult to know what to look for without an understanding the underlying problem. Sometimes questions show no research effort, and sometimes they're just hard to research. That is why closing questions is not a *hostile* action. It's just a normal part of the site, you are not penalized in any way because your question was closed as a duplicate. Don't worry about it. – user229044 Dec 30 '14 at 19:52