James Levinston
James Levinston

Reputation: 3

Built-in function to convert binary to decimal in JavaScript

I'm writing a program to convert binary numbers to decimal numbers in JavaScript. I am wondering if there is a built in way to do this without having to write all of the manual logic. Here's my code:

var from = $("#from").val();
var to = $("#to").val();
var input = $("#input").val().toString();
var output = "";

var invalid = false;
if (input == "") {
    $("#invalid").text("Please enter a number in the input field")
    invalid = true;
}

if (from == "bin" && to == "dec") {
    // check if valid binary digits
    for (var i = 0; i < input.length; i++) {
        if (input.charAt(i) != '1' && input.charAt(i) != '0') {
            $("#invalid").text("You did not enter a valid binary number. Please try again!")
            invalid = true;
        }
    }

    if (!invalid) {
        // QUESTION: find a clean way to convert
    }
}

Upvotes: 0

Views: 1663

Answers (1)

Ben Leitner
Ben Leitner

Reputation: 1532

There is a built in way. You can use the parseInt function:

if (!invalid) {
    output = parseInt(input, 2);
}

Upvotes: 1

Related Questions