convert decimal to binary in jquery

am trying to convert a decimal number to binary in jquery but unable to

         var n = 5;
         var  i = 1;
         var rem = 0;
         var binary = 0;

    while (n!=0) 
     {
       rem= n % 2;
       n= n / 2;
       binary = binary + rem * i;
       i= i * 10;
   }
   alert(binary);

i have used the same formula for converting decimal to binary in other programming languages like c++ and it works just fine but it gives an infinity error here

DEMO

Answers 1

  • After division converts it to integer otherwise it may lead to infinite loop since it won't reaches 0 in some case(number may contain decimal part).

    n= parseInt(n / 2, 10);
    

Related Articles