Jump to content

Recommended Posts

Well here it is, I have a SELECT object, and a TEXT object. I checked them both with a simple alert to see if they worked, and they did.. but he next part didn't. Please help.

 

var answer = parseInt(input.value, base);
alert(input.value + " " + answer);

input = TEXT object. What this code does is: If i type 5 into the TEXT object, the alert will say that the input.value is 5 but the answer variable still says not a number (NaN)

 

Oh and the base variable was 2 at this time.

 

Please help! Thanks!

I think you are misunderstanding the purpose of the second parameter for parseInt().

 

The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number

 

If you specify the radix to be 2, then the value to be parsed must be in the format of a binary number, e.g. "1101" (which would be parsed to the decimal value of 13).

function convertToBase() {
  // Converts depending on selections/inputs
  var input = document.getElementById('number');
  var toBaseObj = document.getElementById('to');
  var fromBaseObj = document.getElementById('from');
  var index = 0;
  var toBase = 2;
  var fromBase = 10;

  index = fromBaseObj.selectedIndex;
  fromBase = (index == 0 ? 10 : index == 1 ? 2 : index == 2 ? 16 : index == 3 ? 8 : 10);
  index = toBaseObj.selectedIndex;
  toBase = (index == 0 ? 2 : index == 1 ? 10 : index == 2 ? 16 : index == 3 ? 8 : 2);
  index = 0;

  var inputValue = parseInt(input.value, fromBase);
  var answer = inputValue.toString(toBase);
  alert("Your conversion of " + input.value + " (to base " + base + ") is: \n" + answer);
}

I don't see errors.

Why don't you start by explaining what you want to achieve? Your first post was only regarding the NaN error you were receiving. I can "assume" you are trying to convert a base 10 number to a base 2, but that is only a guess since you've never stated that. Your last post you state you see no errors but don't state what you want the script to do and what it is doing differently.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.