Search Unity

Convert String to Int in C#

Discussion in 'Scripting' started by varadhan83, Aug 30, 2010.

  1. varadhan83

    varadhan83

    Joined:
    Aug 24, 2010
    Posts:
    21
    Hi,
    I am new to Unity. I am working in Android program. I need to convert String to Int.

    Is there any way to convert String to Int.

    Eg:
    String tempString = "4";

    This tempString i need to convert to Int.

    Thanks
    Varadharaj.
     
    id3644unity likes this.
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,139
    int.Parse, or TryParse.

    --Eric
     
    TZ-, Laniemme, tinylord202 and 4 others like this.
  3. Eagle32

    Eagle32

    Joined:
    Jun 20, 2010
    Posts:
    89
    int.Parse(tempString);

    There is also int.TryParse which I usually use, you can lookup it's usage on google.
     
  4. varadhan83

    varadhan83

    Joined:
    Aug 24, 2010
    Posts:
    21
    Hi,
    I am working on android application. I need difference between "Screen.width" and "Screen.currentResolution.width".

    Thanks,
    Varadharaj.
     
  5. CommunityUS

    CommunityUS

    Joined:
    Sep 2, 2011
    Posts:
    181
    Code (csharp):
    1. // declare a string variable with a value that represents a valid integer
    2. string sillyMeme = "9001";
    3.  
    4. int memeValue;
    5. // attempt to parse the value using the TryParse functionality of the integer type
    6. int.TryParse(sillyMeme, out memeValue);
    7.  
    8. Debug.Log(memeValue);//9001
     
  6. firemyst

    firemyst

    Joined:
    Sep 28, 2013
    Posts:
    3
    wayfarergames, RajneeshG and karljj1 like this.
  7. richardalgor

    richardalgor

    Joined:
    Oct 2, 2013
    Posts:
    2
  8. mael5trom

    mael5trom

    Joined:
    Feb 27, 2014
    Posts:
    16
    int myConvertedInt = int.Parse(<yourstringhere>,System.Globalization.NumberStyles.Integer)
     
  9. berzerk

    berzerk

    Joined:
    Dec 23, 2014
    Posts:
    18
    Just adding another piece to the mix... I found a great method in this thread, in the answer by drudiverse. Here is the code for a very fast conversion from string to int. I added my own overload for char to int as well:

    Code (CSharp):
    1. // Benchmark:
    2. // int.Parse("400")     123.07 ns
    3. // IntParseFast("400")    2.87 ns
    4.  
    5.      public static int IntParseFast(string value)
    6.      {
    7.      int result = 0;
    8.      for (int i = 0; i < value.Length; i++)
    9.      {
    10.          char letter = value[i];
    11.          result = 10 * result + (letter - 48);
    12.      }
    13.      return result;
    14.      }
    15.  
    16.    public static int IntParseFast(char value)
    17.      {
    18.          int result = 0;
    19.          result = 10 * result + (value - 48);
    20.          return result;
    21.      }
     
  10. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,095
    that second method is pretty useless, just evaluates to 'value - 48' every time.
     
  11. berzerk

    berzerk

    Joined:
    Dec 23, 2014
    Posts:
    18
    It is a shortcut to converting char to int. You could do that in the code, but if you use it more than once you'd better have it in a method, which is my case.
     
  12. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,457
    No - his point is that result is initialized to 0. 10 * 0 is always 0 so result is always value - 48
     
  13. aaro4130

    aaro4130

    Joined:
    Jul 15, 2010
    Posts:
    388
    Um.. That's the point? Value is an argument, so it will always purposely evaluate to value - 48.

    The Char '1' = 49
    The Number 1 = 1
    49 - 48 = 1

    The Char '2' = 50
    The Number 2 = 2
    50 - 48 = 2

    And so on.

    Passing the value '1' as a char will give you 1 back as an int fast.


    However, won't it work without multiplication?
    1. public static int IntParseFast(char value)
    2. {
    3. int result = 0;
    4. result = result + (value - 48);
    5. return result;
    6. }
     
  14. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,095
    Just have a single line:
    return value - 48
     
    aaro4130 likes this.
  15. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,457
    Indeed. If we're talking about micro-optimizations (and we are) then there's no reason to do the other stuff.
     
  16. glassoctopus

    glassoctopus

    Joined:
    Aug 4, 2013
    Posts:
    7
    using version 5.4.1f1 of unity.

    here is a piece of my code:
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using UnityEngine.EventSystems;
    4. using System;
    5. using System.Linq;
    6. using System.Collections;
    7. using System.Collections.Generic;
    8. using UnityEngine.UI;
    9. ...
    10.   private int enteredValueCommodityAmount;
    11. ...
    12.   private int setCommodityAmountInt()
    13. {
    14. enteredValueCommodityAmount=int.Parse("123456789");
    15.  
    16. Debug.Log(enteredValueCommodityAmount.GetType());
    17. Debug.Log(enteredValueCommodityAmount);
    18.  
    19. return enteredValueCommodityAmount;
    20. }
    21.  
    this is the error i am receiving:
    FormatException: Input string was not in the correct format

    I have tried:
    Int32.Parse, system.Int32 and many more that I have found in examples of and in the MSDN documentation and all lead back to the same error.

    FormatException: Input string was not in the correct format

    int.TryParse throws this error:
    error CS1501: No overload for method `TryParse' takes `1' arguments


    I was calling my string from a variable, but recently i just tried using a string, like the one above. All to the same effect...

    any ideas?
    What am i missing?
     
    Last edited: Sep 23, 2016
  17. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    4,221
    MV10 likes this.
  18. MV10

    MV10

    Joined:
    Nov 6, 2015
    Posts:
    1,889
    I'm responding to this thread so I can find it again in 2020 and bring it back.
     
    agScreen and Kiwasi like this.
  19. glassoctopus

    glassoctopus

    Joined:
    Aug 4, 2013
    Posts:
    7
    thanks for the link, i checked here:
    Wikipedia
    couldn't remember the tags for newline or code. So it is nice that you provided an answer for the format issue.

    But why the trolling on the question, did I not present the question well?
    I didn't see the need to create a new thread for the same problem, maybe others might find this problem in a similar situation.

    i am missing the "out parameter" in the second error, and this seems to be where the problem lies for TryParse, but for the others above Int32.parse etc i am confused why my string is not valid, i was hoping to get some positive feedback

    But really, Bravo on stating the obvious and only offering advice on the formatting. Thanks so much.
     
    Last edited: Sep 23, 2016
  20. jimroberts

    jimroberts

    Joined:
    Sep 4, 2014
    Posts:
    560
    The threads original question was about how to convert strings to integers. You actually have a new problem as your integer string is not being parsed which warrants a new thread.

    However, with that being said... I don't see any reason for your string to fail the parse. There is a possibility that your NumberStyles are messed up. Is the TryParse method working for you?
     
  21. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,464
    In general we prefer new threads. The engine changes enough that reviving a six year old thread often brings up incorrect information.

    The only reasons I can see for Int.Parse to fail in this manner is if you aren't passing in an int. Are you sure there are no random hidden characters? Also check your number fits inside the Int bounds.
     
  22. glassoctopus

    glassoctopus

    Joined:
    Aug 4, 2013
    Posts:
    7
    Hey jimroberts,
    Thank you for the clarification. On line 14 of the code I posted, I thought that was what i was trying to do.
    Code (csharp):
    1. enteredValueCommodityAmount=int.Parse("123456789");
    This is me trying to convert a string, "123456789" to an int, 123456789.

    this link:
    https://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx

    shows that TryParse requires two arguments, string and "out int result"

    but i am confused how this is supposed to work because,
    TryParse has a return value:

    Return Value

    Type: System.Boolean
    true if s was converted successfully; otherwise, false.

    TryParse returns a Bool. Not an Int.

    this link:
    http://net-informations.com/q/faq/stringtoint.html

    shows that TryParse has an "out" argument, i have never seen this.

    I am guessing that this would be more correct:
    Code (csharp):
    1. private bool validationBool
    2. ...
    3. validationBool=int.TryParse("123456789",out enteredValueCommodityAmount);
    4.  
    So this out is going to assign the int value to this "out" argument?

    Is that how TryParse casts a string to an int?
     
  23. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,139
    The point of TryParse is that it tells you if it worked or not (returns bool) and it modifies the int parameter to contain the parsed value. If there's any possibility that the input could consist of non-numeric characters, no matter how remote, you need to do error checking such as using TryParse.

    --Eric
     
    Kiwasi likes this.
  24. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,464
    The normal way to use TryParse is something like this

    Code (CSharp):
    1. int result;
    2. string input;
    3. if (int.TryParse(input, out result)){
    4.     // Do something with the result
    5. } else {
    6.     Debug.Log ("Not a valid int");
    7. }
     
    Last edited: Sep 23, 2016
    CelticKnight likes this.
  25. jimroberts

    jimroberts

    Joined:
    Sep 4, 2014
    Posts:
    560
    You're missing a closing bracket on line 3. :oops:
     
  26. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,464
    Thanks for the catch. Fixed.

    I haven't been able to find a browser for the phone that does decent syntax checking. ;)
     
  27. glassoctopus

    glassoctopus

    Joined:
    Aug 4, 2013
    Posts:
    7
    Thank you everyone for the help,
    Eric5h5, I am working to grab input from an Input Field set to Content Type > Integer Number. So it seems that TryParse in grabbing data that has already been verified would be redundant?
    Self admittedly not a professional programmer. The TryParse taking an argument then assigning this "out" argument instead and not returning it, but returning a bool, is new to me and was confusing. But i think i got it now.
     
  28. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,139
    Probably, but unless speed is super-critical, it doesn't hurt to check anyway.

    --Eric
     
  29. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    4,221
    It's a common pattern. Physics.Raycast uses it. Dictionaries have TryGet, which is convenient for the same reason.

    In C# 7, it'll be possible to declare the out variable inline:

    Code (csharp):
    1. if (int.TryParse(input, out int result)){
    2.     Debug.Log("found an int: " + result);
    3. }
    Which looks very nice.
     
  30. glassoctopus

    glassoctopus

    Joined:
    Aug 4, 2013
    Posts:
    7
    Thank you, everybody! Here is to learning new stuff... .:)
     
  31. CelticKnight

    CelticKnight

    Joined:
    Jan 12, 2015
    Posts:
    378
    Thankyou for that code excerpt, it's been a life-saver!!! I had no idea how to do what I needed until I saw your code. I've just used it in a small project and it works.

    Thanks a bunch :cool:.
     
    Last edited: Nov 21, 2016
  32. atifsatti040

    atifsatti040

    Joined:
    Jun 8, 2018
    Posts:
    1
    You can use any of the following
    Using the convert class like:
    Code (CSharp):
    1. Convert.ToInt16(tempString );
    2. Convert.ToInt32(tempString );
    3. Convert.ToInt64(tempString );
    or you can use
    Parse or TryParse functions for converting your input string to int. Read more
     
  33. marpione

    marpione

    Joined:
    Apr 16, 2016
    Posts:
    24
    I was trying to convert a string with latter to int and I changed @berzerk 's code and changed it so that I can remove any latter and just allow numbers. Here is the code so for your use.

    Code (CSharp):
    1.  public static int IntParseFast(string value)
    2.     {
    3.         int result = 0;
    4.         string numbers = "1,2,3,4,5,6,7,8,9,0";
    5.         string[] l = numbers.Split(',');
    6.         for (int i = 0; i < value.Length; i++)
    7.         {
    8.             for (int j = 0; j < l.Length; j++)
    9.             {
    10.                 char letter = value[i];
    11.                 //Debug.Log(string.Equals(letter, l[j]) + " " + letter + l[j].ToString());
    12.                 if (string.Equals(letter.ToString(), l[j]))
    13.                 {
    14.                     result = 10 * result + int.Parse(l[j]);
    15.                     Debug.Log(result);
    16.                 }
    17.             }
    18.            
    19.         }
    20.         return result;
    21.     }