Example 1: Convert Decimal to Binary
Output
Step 1: 9/2, Remainder = 1, Quotient = 4 Step 2: 4/2, Remainder = 0, Quotient = 2 Step 3: 2/2, Remainder = 0, Quotient = 1 Step 4: 1/2, Remainder = 1, Quotient = 0 Binary: 1001
In the above program, the user is prompted to enter a decimal number. The number entered by the user is passed as an argument to the convertToBinary() function.
The while loop is used until the number entered by the user becomes 0.
The binary value is calculated by:
bin = bin + rem * i;
Here, rem is the modulus % value of the number when divided by 2 and i gives the place value of the binary number.
Example 2: Convert Decimal to Binary Using toString()
Output
Enter a decimal number: 9 Binary: 1001
In the above program, the user is prompted to enter a number. The parseInt() method is used to convert a string value to an integer.
The JavaScript built-in method toString([radix]) returns a string value in a specified radix (base). Here, toString(2) converts the decimal number to binary number.