开发者

How can I round a C# double nullable type?

开发者 https://www.devze.com 2023-03-08 19:41 出处:网络
I want to round a double? value so that if its value is 2.3 the result should be 2 but if the input is null then th开发者_运维问答e result should be null.There is no direct way to round a nullable dou

I want to round a double? value so that if its value is 2.3 the result should be 2 but if the input is null then th开发者_运维问答e result should be null.


There is no direct way to round a nullable double. You need to check if the variable has a value: if yes, round it; otherwise, return null.

You need to cast a bit if you do this using the conditional ?: operator:

double? result = myNullableDouble.HasValue
               ? (double?)Math.Round(myNullableDouble.Value)
               : null;

Alternatively:

double? result = null;
if (myNullableDouble.HasValue)
{
    result = Math.Round(myNullableDouble.Value);
}


As others have pointed out, it is easy enough to do this as a one-off. To do it in general:

static Func<T?, T?> LiftToNullable<T>(Func<T, T> func) where T : struct
{
    return n=> n == null ? (T?) null : (T?) func(n.Value);
}

And now you can say:

var NullableRound = LiftToNullable<double>(Math.Round);
double? d = NullableRound(null);

And hey, now you can do this with any method that takes and returns a value type.


return d.HasValue ? Math.Round(d.Value) : (double?)null;
0

精彩评论

暂无评论...
验证码 换一张
取 消