0

So I'm trying to convert binary to decimal in Javascript:

    function binToDec(){
        var binary = document.getElementById("binaryInput").value.split("").reverse();
        var toDecimal = function(binary) {

            return parseInt(binary,2);
        }
   }

But it's not working out for me... I'm new to JS so I'm not sure what's going on here.

Also, here is the "binaryInput" reference:

    <td colspan="2"><input id="binaryInput" type="text" name="First Number" onfocus='onFocusInput(this);'></td>

Thanks for any help!

  • @Liam I looked at that one and tried out the code, but it didn't work out for me... – user3013513 Dec 11 '13 at 17:37
  • 2
    1) why are you splitting the value 2) why are you reversing the input 3) `function binToDec(){return parseInt(document.getElementById("binaryInput").value,2);}` should do the trick, obviously I'm not checking for correctness of the input here, for that you could add a RegExp /[01]+/g or something alike. – Charlie Affumigato Dec 11 '13 at 17:37

2 Answers2

0

The problem is that you are splitting the input string. Look at the parseInt documentation:

If string [the value] is not a string, then it is converted to one.

However, converting the array (which is created because you split the string) back to a string results in '1,0,1,0,1,0,0,0', not '10101000'. '1,0,1,0,1,0,0,0' is not a valid binary number and parseInt therefore fails.

If you really want to reverse the input, you should use

document.getElementById("binaryInput").value.split("").reverse().join("");

which generates the correct string. If you don't want to reverse it, use

document.getElementById("binaryInput").value;
Tobias
  • 7,723
  • 1
  • 27
  • 44
0

Your function should look like this:

function binToDec(){
  //get the string from the input element
  var binString = document.getElementById("binaryInput").value;

  //remove any non binary character
  binString = binString.replace(/[^01]+/g,'');

  if(binString>''){
    //if you want it to be reversed: binString = binString.split('').reverse().join('')
    return parseInt(binString,2);
  }
  return 0;
}
Charlie Affumigato
  • 1,017
  • 1
  • 7
  • 10