0

I have this code:

public int GetIntSetting(Settings setting, int nullState)
{
    var s = GetStringSetting(setting);
    if (string.IsNullOrEmpty(s))
        return nullState;
    return int.Parse(s);
}

If the value of s is something like 1.234 then the functions creates an exception.

How can I make it so that if the value of s has a decimal point then the function returns 0?

Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51
Alan2
  • 23,493
  • 79
  • 256
  • 450

3 Answers3

4

Use TryParse:

int parsed;
var result = int.TryParse(data, out parsed) ? parsed : 0;

Or if using C#7.0 with the out var declaration:

var result = int.TryParse(data, int out parsed) ? parsed : 0;

Note that as HimBromBeere commented you will not know when it is 0 because it is not a valid int or because the input is actually the input.

All together:

public int GetIntSetting(Settings setting, int nullState)
{
    var s = GetStringSetting(setting);
    if (string.IsNullOrEmpty(s))
        return nullState;
    return int.TryParse(s, out int parsed) ? parsed : 0;
}
Graham
  • 7,431
  • 18
  • 59
  • 84
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
2

int.TryParse will return false for decimal numbers. This is a bit broader than your question of jiust handling decimal points, but is probably a sensible thing to do anyway:

int x = 0;
Console.WriteLine(int.TryParse("1.234",out x)); // outputs False

So you could change your code to

public int GetIntSetting(Settings setting, int nullState)
{
    var s = GetStringSetting(setting);
    if (string.IsNullOrEmpty(s) )
        return nullState;
    var result = 0;
    if(!int.TryParse(s,out result))
        return 0;
    return result;
}
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • Actually I just realized. I only need to check the string for the existence of a "." I think that would be maybe more clean. – Alan2 Jul 31 '17 at 11:54
  • 3
    So a setting for `abc123$%$£!%"&` is an acceptable `int` to you? – Jamiec Jul 31 '17 at 11:55
  • @Alan If you have another solution to your problem feel free to post an answer yourself. However in this particular case I won´t recommend that because of the previously mentioned comment from Jamiec. – MakePeaceGreatAgain Jul 31 '17 at 12:01
1

I'd propose TryParse testing if it would parse as an int or a double:

double theNumber;
if (Int32.TryParse(s, out theNumber)) return (int)theNumber;
else if (Double.TryParse(s, theNumber)) return 0;

// Here is not an int or double, i.e. return nullState for example
donquijote
  • 1,642
  • 5
  • 19
  • 41
  • Actually I just realized. I only need to check the string for the existence of a "." I think that would be maybe more clean. – Alan2 Jul 31 '17 at 11:54