How is round double type with zero value?

I want to round in half? value, therefore, if there is 2,3, it should be 2, but if there is null, then it must be null.

+3
source share
3 answers

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

You need to drop a little if you do this with a conditional statement ?::

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

As an alternative:

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

As others have noted, it’s quite simple to do this as a one-time use. To do this as a whole:

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

, .

+20
return d.HasValue ? Math.Round(d.Value) : (double?)null;
+2

All Articles