Home > Net >  How to convert non-numeric Strings to Int?
How to convert non-numeric Strings to Int?

Time:10-16

I've been looking for the past 30 minutes just on this one simple question but they all say to use Parse methods when I know they won't work because the string is possibly non-numeric. However, instead of just throwing an error I still want it to give out a number based on the string. Any ideas?

CodePudding user response:

If you just want a number based on the string, and you don't really care which number it is just as long as the string was used to create it, then GetHashCode() may be what you're looking for.

int num = str.GetHashCode();

If two strings are identical, then GetHashCode() will return the same number for both of them. If two strings are different, then it's very likely (but not guaranteed) that GetHashCode() will return different numbers for them.

CodePudding user response:

Do you need any functionality beyond TryParse()?

if( double.TryParse(text, out double x)) 
{
  // use numeric `x` here
} 

or

if( int.TryParse(text, out int i)) 
{
  // use integer `i` here
}
  • Related