javascriptregexnumbersoctal

JavaScript - Preventing octal conversion


I'm taking a numerical input as an argument and was just trying to account for leading zeroes. But it seems javascript converts the number into octal before I can do anything to the number. The only way to work around it so far is if I pass the number as a string initially but I was hoping there'd be another way to convert it after it is passed? So far tried (using 017 which alerted me to the octal behaviour):

017.toString(10) // 15
parseInt(017,10) // 15
017 + "" //15
new Number(017) //15

new Number('017') //17
parseInt('017', 10) // 17

So given

function(numb) {

if (typeof numb === number) {
// remove leading zeroes and convert to decimal
}
else {
 // use parseInt
}

}

'use strict' also doesn't seem to solve this as some older posts have suggested. Any ideas?


Solution

    1. If you take "numerical input", you should always definitely guaranteed have a string. There's no input method in this context that I know that returns a Number. Since you receive a string, parseInt(.., 10) will always be sufficient. 017 is only interpreted as octal if written literally as such in source code (or when missing the radix parameter to parseInt).
    2. If for whatever bizarre reason you do end up with a decimal interpreted as octal and you want to reverse-convert the value back to a decimal, it's pretty simple: express the value in octal and re-interpret that as decimal:

      var oct = 017; // 15
      parseInt(oct.toString(8), 10) // 17
      

      Though because you probably won't know whether the input was or wasn't interpreted as octal originally, this isn't something you should have to do ever.