JavaScript - Preventing octal conversion

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

提交回复
热议问题