r/ProgrammerTIL • u/vivzkestrel • Dec 13 '20
Other TIL that 42..toString(2) converts 42 to binary in Javascript
- https://stackoverflow.com/questions/9939760/how-do-i-convert-an-integer-to-binary-in-javascript
- you add 2 dots and put a base 2 inside the toString method and you get a binary directly
67
Upvotes
43
u/americk0 Dec 13 '20
I think I learned about this a while ago and forgot about it because it seems familiar.
Also for anyone curious like I was, the first dot is the decimal for the number and the second dot is the standard dot in JS. If you only put one dot, JS tries to interpret it as a decimal point and spits out an error because "t" is not a digit. As another example, this code is functionality equivalent to what OP posted:
42.0.toString(2)28
u/ShortFuse Dec 13 '20
It's not really the two dots. You can do
(42).toString(2). It's just JS syntax interprets the first.as a decimal place and the second as accessing the properties ofNumber.The fact that
42,42., and42.0are the same is one of the quirks of JavaScript. A number after the decimal place is optional. You can dovar n = 42.;On a sidenote, you can convert to hexadecimal with
.toString(16).23
u/hotel2oscar Dec 13 '20
Replace 2 with 16 and you get hexadecimal.
2
u/vVv_Rochala Dec 13 '20
is there documentation on this .. operator?
2
u/MattBBitcoin Dec 17 '20
In python you can do format(number, 'b') and it will transform the number to binary :)
0
u/[deleted] Dec 13 '20
[deleted] — view deleted comment