Decimal to binary in JavaScript? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Decimal to binary in JavaScript?

actually, I'm an UI developer trainee and my staff told me to write a JavaScript program to convert the decimal numbers to binary numbers, I can convert by manually but I don't know what syntax should I use in js. I've searched it on google but could not found the easily understandable code.

7th Apr 2017, 7:29 PM
sharfudeen
sharfudeen - avatar
2 Answers
+ 11
This works with me: -------------------------- // Function to convert the number var toBinary = function(decNum){ return parseInt(decNum,10).toString(2); } // Input by user var num = prompt("Enter number"); // Alert with the function toBinary() alert(toBinary(num)); -------------------------- (Source of function: StackOverflow)
7th Apr 2017, 8:53 PM
Maz
Maz - avatar
+ 9
With a for ciclus 2^x untill you pass the number, the x-1 will give you the highest 1, with a second for continue with the next x-1, untill x is 0. This is a low level solution.
7th Apr 2017, 9:17 PM
Emore Anzolin
Emore Anzolin - avatar