简体   繁体   中英

Converting to Int in C# leaves the Value as 0

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;
}

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;
}

假设numberRangeHigh的类型为Decimal,请尝试以下操作:

int DayOffset = Decimal.ToInt32(numberRangeHigh);

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM