0

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
    }
}
1

1 Answer 1

1

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

if (!invalid) {
    output = parseInt(input, 2);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Than you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.