- Home /
How to convert a string to an int?
I've been researching this for a while, but I can't find anything that works or makes sense to me. I'm hoping that someone can dumb this topic down to my level so I can understand it. Here's my problem: I want to change a string to an int in Javascript (NOT C#), and I want to know how I make it do something when it can't convert. I'm trying to use "int.TryParse" so I can tell when the string can't be converted to an int. Here's what I have:
var temp : int = 0;
MaxPlayers = int.TryParse(MaxPlayersField, temp);
Just a reminder, I'm kinda new to this stuff so please don't talk above my head. Thanks in advance!
Answer by robertbu · Jul 29, 2014 at 09:51 PM
TryParse returns a boolean value indicating whether the string could be converted to an int. The place where you want to store the value should be passed as the second parameter. So the code might be:
if (!int.TrayParse(MaxPlayersField, MaxPlayers) {
Debug.Log("Could not convert to a number");
}
Note the '!' at the start of the 'if' clause. You don't indicate what should happen if the string cannot be parsed, so this code just outputs a Debug.Log() message.
Thank you so much! This worked and it seems very simple and easy to use!
Your answer
Follow this Question
Related Questions
converting "int" to "string" 2 Answers
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer
int.parse with decimal? 1 Answer
Parsing a String to a Color 1 Answer