Reputation: 113
I'm trying to convert number lead by 0 to string.
for example
var x = 01127160037
but when I convert it to string, it become 157081631<script>
function myFunction() {
var x = 01127160037;
var res = x.toString();
console.log(res)
}
myFunction();
</script>
I'm expecting to get actual result as "01127160037" in string.
Upvotes: 2
Views: 370
Reputation: 386550
With leading zero, you use octal numbers. To get decimals, you need to convert back to octals and take this string.
If you got a value which can not be an octal number, check if the stringed value contains eight or nine and take this value without conversion instead.
const convert = n => '0' + (/[89]/.test(n.toString())
? n.toString()
: n.toString(8)
);
console.log(convert(01127160037));
console.log(convert(01127160038));
Upvotes: 7