8

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.

3
  • You could also just round the number first, so it's a whole number... Commented Aug 24, 2015 at 14:40
  • boy, this is how questions should be. Simple, with working code that can be tested. Nice. Commented Aug 24, 2015 at 14:42
  • In my now-removed answer I confused AllowThousands with AllowDecimalPoint, where the former can let int.Parse() parse numbers with commas (depending on culture). In some cultures comma is the decimal separator. It does work if the fractional digits only contain zeroes (as documented): ideone.com/stQ9GY. Commented Aug 24, 2015 at 14:44

1 Answer 1

14

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

I did not realize how strict TryParse was. Thanks for your help.
You may want to refine the statement "28.789 is clearly not an int so it fails" somewhat, int.(Try)Parse can handle decimals as long as the fractional digits are all zeroes.
@CodeCaster: Good point. But i haven't said that it fails if the input string contains decimal places.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.