Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TryParse not working when trying to parse a decimal number to an Int

Tags:

c#

int

c#-4.0

I am trying to parse strings that may have a decimal. I'm using Int32.TryParse but it doesn't seem to be working.

Here is my function where I try to parse:

private NumberStyles styles = NumberStyles.Number;
private CultureInfo culture = CultureInfo.CurrentCulture;
public int? ParseInt(string node)
{
    int number;
    if (Int32.TryParse(node, styles, culture.NumberFormat, out number))
    {
        return number;
    }
    return null;
 }

And here is my unit test that is failing

[Fact]
public void TestParseIntWithDecimal()
{
    string provided = "28.789";
    int expected = 28;

    int? actual = _parser.ParseInt(provided);

    Assert.NotNull(actual);
    Assert.Equal(expected, actual);
}

When I run my unit test, null is returned from ParseInt and I don't understand why. I thought TryParse could parse decimal numbers into integer numbers.

like image 524
DFord Avatar asked Aug 24 '15 14:08

DFord


1 Answers

The Parse/TryParse methods are very strict. They don't accept any other types than the one you use as target. 28.789 is clearly not an int so it fails. If you want to truncate the decimal part you still have to parse it to decimal first. Then you can use (int)Math.Floor(num).

private NumberStyles styles = NumberStyles.Number;
private CultureInfo culture = CultureInfo.CurrentCulture;
public int? ParseInt(string node)
{
    decimal number;
    if (decimal.TryParse(node, styles, culture.NumberFormat, out number))
    {
        return (int) Math.Floor(number); // truncate decimal part as desired
    }
    return null;
}
like image 51
Tim Schmelter Avatar answered Nov 14 '22 21:11

Tim Schmelter