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; }
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.