I have a function that takes a number/integer as a parameter, and I'm trying to remove any possible leading zeros from that number before doing anything else in the function. However, numbers with leading zeros seem to be parsed in some way already before I can do something with the function parameter.
So far I tried this:
function numToString(num){
var string = num.toString();
console.log(string);
};
numToString(0011); // output is "9"
numToString(1111); // output is "1111"
I also tried this:
function numToString(num, base){
var string = num.toString();
var parse = parseInt(string, base);
console.log(parse);
};
numToString(0011, 10); // output is "9"
numToString(1111, 10); // output is "1111"
Of course, the second example doesn't work since num.toString()
didn't give my expected outcome in the first place. I don't want to replace the "num" function parameter with a string, but keep it as a number.
Maybe there is something obvious that I'm missing, but I can't figure quite out what it is. I am aware that a number with leading zeros is seen as an octal number, but I would like to know if I can work with the number that is entered as a parameter when it has leading zeros (i.e. it doesn't come from a variable, but is literally entered as a function parameter).
The reason this is happening is because leading a number with a zero makes javascript interpret the number in octal format. There is no way that you can change this interpretation, but if you're getting the value from somewhere as a string you could use parseInt(string, 10)
We can do this string conversion ourselves and then parse it in base 10 like so:
let number = 0011
console.log(parseInt(number.toString(8),10))
The other part of your question asks if you can throw when an octal number is entered.
'use strict'
does just this:
Sixth, a strict mode in ECMAScript 5 forbids octal syntax. The octal syntax isn't part of ECMAScript 5, but it's supported in all browsers by prefixing the octal number with a zero:
0644 === 420
and"\045" === "%"
. In ECMAScript 2015 Octal number is supported by prefixing a number with"0o"
. i.e.var a = 0o10; // ES2015: Octal
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode