Function to convert decimal to Binary in Javascript.

This is my function that converts decimal to binary in javascript.


function decToBin(i) {
let buf='';
let ret='';
while(i > 0) {
if((i%2) === 0) {
buf+='0';
} else {
buf+='1';
}
i = parseInt(i / 2);
}
const l = buf.length;
for(let x = 0; x < l; x++) {
ret+=buf[l-x-1];
}
return ret;
}

decToBin(10);

result = 1010

Leave a comment