-1

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

Craftx398
  • 341
  • 1
  • 2
  • 13
  • 1
    duplicate of http://stackoverflow.com/questions/9939760/how-do-i-convert-an-integer-to-binary-in-javascript – sumit Feb 24 '17 at 05:37
  • Possible duplicate of [how do I convert an integer to binary in javascript?](http://stackoverflow.com/questions/9939760/how-do-i-convert-an-integer-to-binary-in-javascript) – sumit Feb 24 '17 at 05:41
  • There is no decimal here. The input is already binary. – user207421 Aug 22 '17 at 04:25

2 Answers2

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);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

The problem here is

 n = n / 2;

because in JavaScript (jQuery) the division returns a float number, not an integer.

So you have first 2.5, then 1.25, 0.625, 0.3125, and so on, so your condition is not satisfied.

To avoid this you just need to parse to integer the float result

n = parseInt(n / 2);