1

For example if I have the folowing javascript code:

let num = 00111;
console.log(num.toString());

This would give me '73'

Yet I would want '00111'

technophyle
  • 7,972
  • 6
  • 29
  • 50
  • 2
    You can do `let num = '00111';` or `console.log(num+'')` – Martijn Jan 31 '20 at 15:54
  • 3
    @Martijn the issue is the octal-literal, however. – Alex Huszagh Jan 31 '20 at 15:55
  • Numbers are represented internally as binary floating-point values; there are no leading zeros in the actual representation. What you're looking for is a means of formatting numeric values as strings. – Pointy Jan 31 '20 at 15:56
  • Alexander is right, leading 0s in an int is *not* an integer, so it needs to be defined as a string otherwise there will be conversions before you can get to it. – Sterling Archer Jan 31 '20 at 15:56
  • Well, it's an integer, just with radix 8, not 10. Javascript supports octal literals without the decimal point only, so `0111.0` (which throws an error) differs from `0111`. – Alex Huszagh Jan 31 '20 at 15:57
  • @Paulvitalis How come 00111's "equivalent string" is '003'? – technophyle Jan 31 '20 at 15:57
  • @technophyle that was a typo I made. What I meant is converting 00111 to a string of '00111' – Paulvitalis Jan 31 '20 at 16:07

2 Answers2

0

The issue with why the number is not-as-you-expect is because leading 0s in an integer literal tell Javascript the number is an octal literal, an integer with radix 8.

To get what you want, you can either remove the leading zeros from the literal and then add them back later:

let num = 111;
console.log('00' + num.toString());

Or you can store the value as a string, and parse it:

let value = '00111':
let num = parseInt(value);  // assumes radix 10.
console.log('00' + num.toString());

If the goal is merely counting bits represented by 1s (which would explain the '3' in the example), you can write a helper function that would count the number of 1s in a string, and then use that to extract the value, as has been done here.

If the goal is a literal binary number (7, not 3), then you can use binary literals:

let num = 0b00111;
console.log(num);   // 7
console.log(num.toString(2));   // 111
Alex Huszagh
  • 13,272
  • 3
  • 39
  • 67
0

Number.prototype.toString() has a radix parameter that converts your string to any number in that radix.

So, if you want to convert your number to a string value of its JavaScript octal notation, you can do this:

let num = 00111;
let str = `00${num.toString(8)}`;
console.log(str);
technophyle
  • 7,972
  • 6
  • 29
  • 50