JS Example for Beginners: JavaScript Program to Convert Decimal to Binary

Hits: 49

(JavaScript programming Example for Beginners)

JavaScript Program to Convert Decimal to Binary

In this example, you will learn to write a JavaScript program that converts a decimal number to a binary number.

 


Example 1: Convert Decimal to Binary

// program to convert decimal to binary
function convertToBinary(x) {
    let bin = 0;
    let rem, i = 1, step = 1;
    while (x != 0) {
        rem = x % 2;
        console.log(
            `Step ${step++}: ${x}/2, Remainder = ${rem}, Quotient = ${parseInt(x/2)}`
        );
        x = parseInt(x / 2);
        bin = bin + rem * i;
        i = i * 10;
    }
    console.log(`Binary: ${bin}`);
}

// take input
let number = prompt('Enter a decimal number: ');

convertToBinary(number);

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 and i gives the place value of the binary number.


Example 2: Convert Decimal to Binary Using toString()

// program to convert decimal to binary

// take input
let number = parseInt(prompt('Enter a decimal number: '));

// convert to binary
let result = number.toString(2);

console.log('Binary:' + ' ' + result);

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.

 

 

JS Example for Beginners: JavaScript Program to Convert Decimal to Binary

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.