JavaScript - Preventing octal conversion

前端 未结 3 810
天命终不由人
天命终不由人 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:47

    JavaScript interprets all numbers beginning with a 0, and containing all octal numerals as octals - eg 017 would be an octal but 019 wouldn't be. If you want your number as a decimal then either
    1. Omit the leading 0.
    2. Carry on using parseInt().

    The reason being is that JavaScript uses a few implicit conversions and it picks the most likely case based on the number. It was decided in JavaScript that a leading 0 was the signal that a number is an octal. If you need that leading 0 then you have to accept that rule and use parseInt().

    Source

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-12 02:04

    If you type numbers by hand to script then not use leading zeros (which implicity treat number as octal if it is valid octal - if not then treat it as decimal). If you have number as string then just use + operator to cast to (decimal) number.

    console.log(+"017")
    
    if (021 < 019) console.log('Paradox');

    The strict mode will not allow to use zero prefix

    'use strict'
    
    if (021 < 019) console.log('Paradox');

    0 讨论(0)
提交回复
热议问题