JavaScript How to Convert Decimal to Binary Easily
Use the JavaScript method
number.toString(2) to convert a decimal number to its binary string representation, for example, (10).toString(2) returns '1010'.Examples
Input5
Output'101'
Input10
Output'1010'
Input0
Output'0'
How to Think About It
To convert a decimal number to binary, think of representing the number in base 2 instead of base 10. JavaScript provides a simple way to do this by converting the number to a string in base 2 using
toString(2).Algorithm
1
Get the decimal number input.2
Use the built-in method to convert the number to a binary string by specifying base 2.3
Return or print the binary string.Code
javascript
const decimalNumber = 10; const binaryString = decimalNumber.toString(2); console.log(binaryString);
Output
1010
Dry Run
Let's trace converting decimal 5 to binary using toString(2).
1
Start with decimal number
decimalNumber = 5
2
Convert to binary string
binaryString = (5).toString(2) => '101'
3
Output the result
console.log(binaryString) prints '101'
| Decimal Number | Binary String |
|---|---|
| 5 | 101 |
Why This Works
Step 1: Using toString with base 2
The toString method converts a number to a string in the specified base, here base 2 for binary.
Step 2: Binary representation
The method returns the binary digits as a string, which is easier to use or display.
Alternative Approaches
Manual division method
javascript
function decimalToBinary(num) { let binary = ''; while (num > 0) { binary = (num % 2) + binary; num = Math.floor(num / 2); } return binary || '0'; } console.log(decimalToBinary(10));
This method shows the step-by-step division by 2 but is longer and less efficient than using toString(2).
Using bitwise operators
javascript
function decimalToBinary(num) { return (num >>> 0).toString(2); } console.log(decimalToBinary(10));
This uses unsigned right shift to handle numbers safely and then converts to binary string.
Complexity: O(log n) time, O(log n) space
Time Complexity
The conversion depends on the number of bits in the decimal number, which is proportional to log base 2 of the number.
Space Complexity
The output string length grows with the number of bits, so space is also O(log n).
Which Approach is Fastest?
Using toString(2) is fastest and simplest; manual methods are slower and more complex.
| Approach | Time | Space | Best For |
|---|---|---|---|
| toString(2) | O(log n) | O(log n) | Quick and easy conversion |
| Manual division | O(log n) | O(log n) | Learning how binary works |
| Bitwise operators | O(log n) | O(log n) | Handling unsigned integers |
Use
number.toString(2) for a quick and simple decimal to binary conversion in JavaScript.Forgetting to specify base 2 in
toString returns the decimal string instead of binary.