JavaScript - Preventing octal conversion

三世轮回 提交于 2019-11-27 08:19:44

问题


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?


回答1:


  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.




回答2:


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




回答3:


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');


来源:https://stackoverflow.com/questions/34394273/javascript-preventing-octal-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!