Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

String to int...

Discussion in 'Scripting' started by klindeman, Sep 19, 2005.

  1. klindeman

    klindeman

    Joined:
    Jun 13, 2005
    Posts:
    295
    I am having some difficulties getting a string converted to an int in JavaScript. Say I have some code like this:

    Code (csharp):
    1. var numberString "12345";
    2. var numberInt;
    3. numberInt = int.Parse(numberString);
    4. numberInt++;
    5. // numberInt now is 12346
    Thats what should happen. I converted the C# code from here to that JS. Problem is, it seems like it doesn't know that numberString is the right type of string or something, because it outputs the error "System.FormatException: Invalid format" on the int.Parse() line.
     
  2. freyr

    freyr

    Joined:
    Apr 7, 2005
    Posts:
    1,148
    I assume that the missing = operator on line 1 is just a transcription error.... :p

    For some reason int.Parse (Or rather System.Int32.Parse) is defined to return System.Object instead of an int.

    If you explicitly define the type of numberInt, it should work:
    Code (csharp):
    1.  
    2. var numberInt: int;
    3.  
    ... although the InvalidFormat exception is raised when you give Parse a string that can't be parsed as a number, so I have a suspicion that you already were that far.
     
  3. nmceri

    nmceri

    Joined:
    Aug 4, 2005
    Posts:
    56
    I'm trying to go the other way around.
    Code (csharp):
    1.  
    2. var currentInt = 0;
    3. var currentStr = "0";
    4.  
    5. if (currentInt != 10){
    6.     currentInt++;
    7.     currentStr = currentInt.toString;
    8. }
    9.  
    I get the error: 'toString' is not a member of 'System.Int32'

    Is this the proper way to do it?
     
  4. Joachim_Ante

    Joachim_Ante

    Unity Technologies

    Joined:
    Mar 16, 2005
    Posts:
    5,203
    currentInt.ToString();
     
  5. nmceri

    nmceri

    Joined:
    Aug 4, 2005
    Posts:
    56
    Thank you Joachim, but this is giving me some trouble in my array.
    Code (csharp):
    1.  
    2. var currentInt = 0;
    3. var currentStr = "0";
    4.  
    5. function Update () {
    6.  
    7.     if (currentInt != 10){
    8.         var node = Array();
    9.         node.Add(currentInt);
    10.         node[currentInt] = GameObject.Find (currentStr);
    11.         currentInt ++;
    12.         currentStr = currentInt.ToString();
    13.     }
    14. }
    15.  
    It appears the original variable goes through nicely, but once i add one and try to go through a second time it gives me "Array index is out of range."

    Is this properly converting into a string? If yes, did I miss something else?
     
  6. Joachim_Ante

    Joachim_Ante

    Unity Technologies

    Joined:
    Mar 16, 2005
    Posts:
    5,203
    You are recreating the array from scratch every frame. Thus it will always start out zero size then you resize it to contain 1 element.
     
  7. nmceri

    nmceri

    Joined:
    Aug 4, 2005
    Posts:
    56
    DOH! Thank you once again.
     
  8. deram_scholzara

    deram_scholzara

    Joined:
    Aug 26, 2005
    Posts:
    1,043
    okay... um... so how do you convert a string like "23" to the Int 23? Seems like this thread only went the other way around.
     
  9. User340

    User340

    Joined:
    Feb 28, 2007
    Posts:
    3,001
    Try this:

    Code (csharp):
    1. var myString : String = "23";
    2.  
    3. function Start ()
    4. {
    5.      var theInt : int = parseInt (myString);
    6. }
     
  10. deram_scholzara

    deram_scholzara

    Joined:
    Aug 26, 2005
    Posts:
    1,043
    Edit: oops! nevermind... just forgot the "var" at the beginning of line 8.


    Hmm... I just tried it in my script:
    Code (csharp):
    1. var widthFeet = "25";
    2. //var heightFeet = "10";
    3. //var depthFeet = "30";
    4.  
    5.  
    6. function OnGUI () {
    7.     var tempWidth = GUI.TextField (Rect (10, 10, 200, 20), widthFeet, 2);
    8.     tempWidthInt : int = parseInt (tempWidth);
    9.     if (tempWidthInt > 0  tempWidthInt <= 36) {
    10.         widthFeet = tempWidth;
    11.     }
    12.  
    13. }
    and I get:
    and
     
  11. CupOfJoe

    CupOfJoe

    Joined:
    Aug 5, 2010
    Posts:
    3
    Since I was wondering the same thing in C#...

    In C#, the code is:
    Code (csharp):
    1. int intSix = 6;
    2. string strSix = intSix.ToString();
    3.  
     
  12. iceshaft07

    iceshaft07

    Joined:
    Jul 23, 2010
    Posts:
    293
    You forgot the weord "var":

    var tempWidthInt : int = parseInt (tempWidth);

    Edit:

    Didn't see your edit :)

    Edit 2:

    I did not like the above ways of converting between int and float. I was unable to get int.TryParse(string,int) to work, System.Int32.TryParse(string,int) did not work, and while parseInt (which is completely undocumented from what I can tell) failed on strings which contained characters.

    This is the method I used:

    Code (csharp):
    1.  
    2.         try
    3.         {
    4.         var myInt : int = System.Convert.ToInt32(levelToLoad);
    5.         }
    6.         catch (err)
    7.         {
    8.         //code to handle non-numeric strings here
    9.         }
    10.  
    For new comers, check out the .Net Framework documentation on System.Convert.
     
  13. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Those are the same thing. Also, it works fine:

    Code (csharp):
    1. var aString = "123456";
    2. var stringVal = 0;
    3. if (!int.TryParse(aString, stringVal))
    4.     Debug.Log ("Numbers only!");
    5. else
    6.     Debug.Log (stringVal);
    --Eric
     
  14. ngochaihackerpro

    ngochaihackerpro

    Joined:
    Oct 13, 2010
    Posts:
    7
    Pls help me to convert string to Int (C#);
    such as : "23" >>> 23;

    i can't use :" int.Parse("23") "
     
  15. Chris-Sinclair

    Chris-Sinclair

    Joined:
    Jun 14, 2010
    Posts:
    1,326
    You should be able to use int.Parse("23"), perhaps you wrote it wrong in your code?

    Try this instead:
    int number = System.Int32.Parse("23");
     
  16. ngochaihackerpro

    ngochaihackerpro

    Joined:
    Oct 13, 2010
    Posts:
    7
    Thanks FizixMan very much.
     
  17. Themp

    Themp

    Joined:
    Nov 8, 2011
    Posts:
    96
    The reasons why they dont work is because you guys dont declare the variables.. i see var i = "stuff" and things like that.. it works better if you type var i:String = "stuff"; it's also less intensive for unity and it's easier to see whats what...
     
  18. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    That's completely wrong. var i = "stuff" is exactly the same as var i : String = "stuff". It doesn't work better or worse either way, nor is it any more or less intensive either way. It's called "type inference". I would also disagree that it's any easier to see what's what, at least in this case, since putting something in quotes makes it very obvious that it's a string, especially with syntax coloring.

    --Eric
     
  19. uberubert

    uberubert

    Joined:
    Mar 22, 2012
    Posts:
    1
    That's what everyone thinks. Then they get some programming experience and learn how to actually program efficiently. You shouldn't reply to programming questions based entirely on what you think is right. Programming requires perfect precision knowledge, and does not work well on feelings. Atleast not until someone makes a proper AI of some sort...

    While you are correct that the end result is essentially the same between var i = "stuff", and var i:String = "Stuff", that will not hold true once your project turns resourcedemanding enough for you to want to savor every little bit of cpu-cycle you can on every nook and cranny to gain better fps.
    var i:String = "Stuff"; // this one is Ever so slightly faster, and is in fact part of the optimization process you should do on every project.

    Sure, simple projects won't need as much attention to optimizations as larger ones, but it's a good programming habit to always declare your types. Even when it's not needed.
     
  20. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    I was always under the impression that type inference only cost you in compile time and not run time performance.

    Yay replying to a thread from 2005!
     
  21. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    I'm replying based on facts.

    Duh. That's why I'm using easily verifiable facts; I suggest you do the same. All you're going off of is a feeling.

    It's not "essentially the same", it is the same. Go look at the compiled CIL code.

    Untrue.

    Wrong. It's not even 1 CPU cycle faster, since all the work is done when the code is compiled, not when it's running. Look at the compiled CIL code, or at least run a benchmark.

    Type inference takes care of declaring types for you. In some cases type inference can introduce ambiguity when reading code, and in those cases you shouldn't use it. However, I don't know about you, but if I read var foo = "blah", I have an approximately 0% chance of being confused as to what the type is. Also, don't bother trying to lecture someone when you don't know what you're talking about.

    --Eric
     
  22. tonyd

    tonyd

    Joined:
    Jun 2, 2009
    Posts:
    1,224
    Perhaps you shouldn't reply until you look at someones post count. Over 16,000 posts AND a moderator, I think Eric knows what he's talking about...
     
  23. HardDisk

    HardDisk

    Joined:
    Mar 27, 2012
    Posts:
    1
    A quick look in the Unity Script Reference shows that JavaScript's dynamic typing does have an impact on performance. Typing a JS variable without its type might lead to one reusing the variable and losing UnityScript's type inference. I think it's a better practice to type "#pragma script" at the top of the the JS script and always declare the type of each variable.

    Typing the type of the variable also leads to a quicker rewrite of the JS code to C#.

    http://unity3d.com/support/documentation/ScriptReference/index.Performance_Optimization.html

    But then again, I have only one post, so who am I?
     
  24. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    The code under discussion isn't dynamic typing, it's type inference - not the same thing.

    It's generally agreed that it can be a dangerous habit sometimes due to the reasons you cited - but for primitive types (that typically can be safely inferred) you shouldn't lose performance.

    I'd also argue that if you're re-using variable names in the same scope you've got bigger issues.
     
    Last edited: Mar 27, 2012
  25. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Yes. However, we are not talking about dynamic typing here. We are talking about type inference.

    Code (csharp):
    1. var foo = 5;
    2. // NOT dynamic typing
    3. // foo is statically typed as an int
    4. // The type cannot be changed later
    5. // It is EXACTLY as fast as "var foo : int = 5;" because it IS the same
    No. The only possible way to not have type inference is if you don't supply a type or a value.

    Code (csharp):
    1. var foo; // Dynamic typing!
    No, it doesn't make any difference since type inference works the same in both languages.

    Code (csharp):
    1. // JS
    2. function Start () {
    3.     var foo = 5;
    4. }
    Code (csharp):
    1. // C#
    2. public void Start () {
    3.     var foo = 5;
    4. }
    Somebody who apparently doesn't understand type inference. ;) Really, it's very simple: if you supply a value when declaring the variable, the compiler looks at the type of the value, and makes the variable be that type. That's all. It's useful when the type is obvious from the value being supplied:

    Code (csharp):
    1. var foo = Vector3.zero; // The type is Vector3, duh.
    2. var foo : Vector3 = Vector3.zero; // Vector3 is written twice. Cluttered, useless.
    It's not useful when the type isn't obvious:

    Code (csharp):
    1. var foo = SomeKindOfFunction(); // Well, what is it? No clue, would have to look at the function.
    2. var foo : float = SomeKindOfFunction(); // OK, now I know!
    --Eric
     
  26. nevaran

    nevaran

    Joined:
    May 21, 2010
    Posts:
    247
    Ive got a bit more complicated:

    var number : int;

    function Update(){
    number = number + Input.inputString;
    }



    it is supposed to save the int number + the newly typed one

    any solutions guys?
     
  27. wolfhunter777

    wolfhunter777

    Joined:
    Nov 3, 2011
    Posts:
    534
    You could try Int.Parse or Int.TryParse. Int.Parse will return a null if the string given cannot be turned into an integer. Int.TryParse returns a boolean. If it can parse, it will assign the second argument the value of the parsed string.
     
  28. Fattie

    Fattie

    Joined:
    Jul 5, 2012
    Posts:
    476
    "Int.Parse will return a null if the string given cannot be turned into an integer"

    Wolf, that is wrong. It will crash.

    http://msdn.microsoft.com/en-us/library/b3h1hf19.aspx

    FormatException: Input string was not in the correct format
    at System.Int32.Parse (System.String s) [0x00000] in <filename unknown>:0
    at CreateVisuals._badDD (System.String ss) [0x00000] in <filename unknown>:0
    at CreateVisuals._setOKAppropriately () [0x00000] in <filename unknown>:0
    at CreateVisuals.beginForm () [0x00000] in <filename unknown>:0
    at SLIPopup.showTheCreateForm () [0x00000] in <filename unknown>:0
    at SLIPopup.clickedCreate () [0x00000] in <filename unknown>:0
    at SLIVisuals+$buttonNamedPressed$1739+$.MoveNext () [0x00000] in <filename unknown>:0

    You always must use the annoying Int.TryParse to get anything done.

    As a general rule, unfortunately int.Parse should never, ever be used in Unity projects as it will simply crash when the input is not perfect
     
    Last edited: May 6, 2013
  29. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    If you can guarantee that the string input is only numeric, then you can use Int.Parse. Use TryParse if you're not 100% sure. ParseInt doesn't exist in Unity; you're referencing a Jscript page, which isn't relevant. (Well, Unityscript has a "parseInt" function, but it's just a wrapper for Int.Parse.)

    --Eric
     
  30. Fattie

    Fattie

    Joined:
    Jul 5, 2012
    Posts:
    476
    Ahhh ! it's a wrapper, of course -- cheers

    I was wondering, "how do you know that?" .. I'm always puzzled by that sort of thing as (as far as I know) in this example parseInt in UnityScript is not documented anywhere.

    I mean ... can one "see the headers" at least for Unityscript, somewhere, or ? In the early days of Unity did the Unity guys make a statement somewhere "here are the functions in Unitysxript!" or .. ?! You can probably see what I mean!

    I've always wondered about this! I must have been interesting in the first days of Unity3D.

    ---

    "If you can guarantee that the string input is only numeric" .. you can't guarantee anything Wolf, only use TryParse (or I guess catch the exceptions)

    Put it this way, don't use Int.Parse unless you are catching exceptions, Wolf
     
  31. wolfhunter777

    wolfhunter777

    Joined:
    Nov 3, 2011
    Posts:
    534
    Erm...Just wanna point out that I made that post last year. Yeah, I wasn't that smart back then, I ensured I would always be using numeric values for string because it was for a calculator in Unity. Next, Eric made that reply, not me =P

    Yes, I thank you for pointing it out my mistake but you can guarantee some instances which you will only input integer values (calculator anyone?). If it is not influenced by the user in any way, you will know what data type the input will be.
     
  32. Fattie

    Fattie

    Joined:
    Jul 5, 2012
    Posts:
    476
    "Erm...Just wanna point out that I made that post last year"

    lol ok well delete it or something! it's wrong. (i edited out a mistake in my post, why leave errors on the net?)

    "Next, Eric made that reply, not me =P"

    Right, but I was addressing you.

    "but you can guarantee some instances which you will only input integer values (calculator anyone?)"

    This is completely, absolutely, totally, fully, 100% wrong, in a computer science sense, or in any project you will ever work on for yourself or others.

    You can guarantee nothing.

    Whenever you are dealing with ASCII, never assume anything.

    A simple example is, you may be thinking of using the "calculator input" style keyboard available in iOS or Android.

    Those change constantly from version to version, device to device, user setting to user setting, rotation to rotation, and you never know

    (A typical gotchya is the "telephone-input" style on iOS .. but on ipad (no telephone) you just get a normal keypad - crash.)

    Another simple example is the entire nature of the industry from top to bottom is today modularity .. you may think "you're writing" the keyboard input screen so "you just know" because you're "careful" it will never have a space or something ... but what about next week when another team takes over that section, or you replace it with some widget from Android, or whatever?

    Anyway there is no need to go in to it at length with examples ...... don't assume things in computing. Couldn't be more basic.

    "Put it this way, don't use Int.Parse unless you are catching exceptions"

    {Sure, you can dream up whacky examples where you would run without catching errors, "I am doing scientific computing and the input ..." blah blah. That'ss irrelevant in unity, games, mobile apps, UI, consumer products, etc.}
     
  33. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    I see you already corrected the "must always use TryParse" idea by mentioning catching exceptions, so that saves me the bother. ;) Just note that throwing an exception isn't the same as crashing.

    --Eric