How to convert number from decimal to binary in Javascript and React?

Total
0
Shares

To convert a number from decimal to binary, you can use (num >>> 0).toString(2). This will work in JavaScript, JQuery, React, React Native, VueJs and every other javascript variant framework in the market.

>>> is a bitwise operator which is also know as zero fill right shift. Here we are using it to convert the input number into bits so that we can get the appropriate output using toString.

const convertDecimalToBinary = (decimalNumber) => {
  if(!isNaN(decimalNumber))
    return (decimalNumber >>> 0).toString(2);
  return false;
}

    Tweet this to help others

The above code will first type check the input and confirm if it is a decimal number. If it’s not then it will return false. If it’s a string then you can first convert it to a number.

Live Demo

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like