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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With