Jump to content

Convert variable to integer?


afish674
 Share

Recommended Posts

I have quite a long script which computes various things and then outputs some numbers. I want to make a function at the end of the script that uses these numbers. However, I want it so that this function can be used stand alone, without the rest of the script. Therefore using a variable to hold the final outputted numbers wouldn't work, because it would lose reference to the outputted numbers if moved away from the rest of the script. I wondered if there is a way to change variables into integers to get around this? Example:

//Variables outputted from rest of scriptvar x = 3;var y = 7;//Convert "x" and "y" into 3 and 7function add(){var answer = 3+7;document.write(answer);}

Obviously the variables x and y in this example will have been extracted from the previous parts of the script and won't always be the same, otherwise you'd just swap them with 3 and 7. The reason for me wanting to do this, is that I want users to be able to embed this function into their own web pages, but I don't want the long script beforehand. The only relevent bit would be the final function. Thanks for your help!

Edited by afish674
Link to comment
Share on other sites

If they're integers to start off, then they should remain integers. If you were extracting them from a form input, then you would need to cast them to numbers using the Number() function. But why are you using global variables? You should be passing them as parameters to the function. Beware of the document.write() method: If you call it after the page finishes loading it will erase everything on the page. Casting variables to numbers:

var a = "1";a = Number(a); // a is now cast to number type

If you want to force it to be an integer:

var a = "1.2";a = parseInt(a) // a is now case to number with value 1

Link to comment
Share on other sites

Ah I see, I'm not actually at the stage where I need to do this yet, I'm just planning ahead. I'll use that approach though. Thanks. I wasn't actually going to use the document write function, it was just a means of doing something with data held by the variable in the example. Thank you :)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...