Solved

# So here is a interesting question

Posted on 2014-01-19
155 Views
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.
0
Question by:stargateatlantis

LVL 82

Accepted Solution

leakim971 earned 250 total points
Test page : http://jsfiddle.net/uLH2B/
``````var d = 8;
var b = "";
while(d>0) {
b = d%2 + b;
d = d>>1;
}
``````
0

LVL 82

Expert Comment

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.

http://www.w3schools.com/js/js_datatypes.asp
0

LVL 42

Assisted Solution

Rob Jurd, EE MVE earned 250 total points
This converts the decimal part as well:

http://jsbin.com/uKAMiXUC/1/edit?js,console

``````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 );
``````
0

## Featured Post

### Suggested Solutions

Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…