-1

I'm trying convert decimal? to int and storing the result in "DayOffset". But because of some reason the value of "DayOffset" is getting set to 0 when I run my code. A value is passed in numberRangeHigh as 4

This is what my code looks like:

int DayOffset:
try
{
    parseSuccess = int.TryParse(numberRangeHigh.ToString(), out DayOffset);
}
catch (Exception ex)
{
    _foundationService.LogBusinessError(null, new ParameterBuilder(), ex.Message.Replace(" ", "_"));
    return false;
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Jaspreet Deol
  • 115
  • 1
  • 1
  • 12
  • 4
    `TryParse` doesn't throw an exception if the parse fails - it just doesn't fill in the `out` parameter. In this case it means that `DayOffset` is left with the default value of 0. See this post: http://stackoverflow.com/questions/405619/convert-string-to-int-and-test-success-in-c-sharp?rq=1 – BJ Myers May 01 '15 at 22:38
  • 3
    Running the code in the debugger would have shown you what @BJMyers just figured out by looking at your code. Learning to use a debugger will teach your eyes to become more like those of BJMeyers. – John Saunders May 01 '15 at 22:40
  • When I try to parse a `decimal?` value of `4` that way, the value in `DayOffset` ends up `4`, just as expected. Converting the value to a string and parse it is an odd way of doing it, and only supports values that have no fractional part, but it does work for the case given. – Guffa May 01 '15 at 22:41
  • Thanks, I would try removing the part where its converting the value to string. I don't even need that. – Jaspreet Deol May 01 '15 at 22:47

3 Answers3

2

Why are you converting to string at all? To convert decimal? to int, you should just use a cast:

int dayOffset = 0;
if (numberRangeHigh != null)
    dayOffset = (int)numberRangeHigh.Value;

The code above will truncate the decimal, so 4.7 would become 4. If you want to round, use Convert.ToInt32 instead:

 dayOffset = Convert.ToInt32(numberRangeHigh.Value);

As a side note, the correct way to use TryParse is this:

int DayOffset:
if (!int.TryParse(numberRangeHigh.ToString(), out DayOffset))
{
    // Handle error...
    return false;
}
AJ Richardson
  • 6,610
  • 1
  • 49
  • 59
0

Assuming numberRangeHigh is of type Decimal, try this:

int DayOffset = Decimal.ToInt32(numberRangeHigh);
sheppe
  • 708
  • 5
  • 12
0

For any nullable struct (you mentioned it was a decimal?), it's often a good idea to first check the .HasValue property (in case it's null). You could do something like this:

int dayOffset = (numberRangeHigh.HasValue) ? Convert.ToInt32(numberRangeHigh.Value) : 0;
Rufus L
  • 36,127
  • 5
  • 30
  • 43