JavaScript - Preventing octal conversion

前端 未结 3 817
天命终不由人
天命终不由人 2020-12-12 01:21

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 anythi

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-12 01:50

    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.

提交回复
热议问题