I want to call a function parsing a number with some zeros at the left to string. But JavaScript is automatically changing the number base.
This is what I'm trying to do:
function printNum(num) {
return num.toString()
}
console.log(printNum(00000100010))
//32776
console.log(printNum(0555))
//365
I'm expecting "100010" or "00000100010" and "555" or "0555". Is that possible?
CodePudding user response:
Because of how JavaScript works, a number that starts with 0 is base 8 if it only contains digits 0-7 (except for 0x
, 0b
, and 0o
, bases 16, 2, and 8, respectively, which throw SyntaxErrors for invalid characters), otherwise it silently uses the decimal number with the zeros at the beginning chopped off. You can't change that, that's just the specification.
If you're wanting to preserve the zeros, the simple way is to just pass in a string originally.
function printNum(num) {
return num.toString()
}
console.log(printNum("00000100010"))
//00000100010
console.log(printNum("0555"))
//0555
You can also define your function to take in a length to pad 0's to or a number of zeros to pad at the start.
function printNum(num, minLength) {
return num.toString().padStart(minLength, "0");
}
console.log(printNum(100010, 11))
//00000100010
console.log(printNum(555, 4))
//0555
function printNum(num, prefixLength) {
return "0".repeat(prefixLength) num.toString()
}
console.log(printNum(100010, 5))
//00000100010
console.log(printNum(555, 1))
//0555