• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 171
  • Last Modified:

So here is a interesting question

So did a interview and the question was without using any native browser functions convert a decimal to binary format in JavaScript.   I didn't know that off hand.
2 Solutions
Test page : http://jsfiddle.net/uLH2B/
var d = 8;
var b = "";
while(d>0) {
    b = d%2 + b;
    d = d>>1;
alert( b );

Open in new window

Dave BaldwinFixer of ProblemsCommented:
Since javascript is weakly typed like PHP is, I usually just add 0 or mulitply by 1.  But then... javascript doesn't actually have a 'decimal' format.  It's strings or numbers with automatic provisions for int or float.

RobOwner (Aidellio)Commented:
This converts the decimal part as well:


var n = "8.75";
var a = n.split(".");
var i = a[0]*1;
var den = 1;
for (j=0;j<a[1].length;j++) {
  den = den * 10;
var d = a[1]/den;

var b1 = "";
var b2 = "";

while(i>0) {
  b1 = i%2 + b1;
  i = i>>1;

var tmp = 0;
while(d>0) {
  tmp = ("" + d*2 + "").split(".");
  b2 = b2 + tmp[0];
  d = tmp[1] / 10;
console.log( b1 + "." + b2 );

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now