Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How round double nullable type?

Tags:

c#

I want to round double? value, so if there is 2,3 should be 2 but if there is null then should be null.

like image 365
kosnkov Avatar asked May 26 '11 17:05

kosnkov


People also ask

Does Math round return a Double?

Rounds a double-precision floating-point value to the nearest integral value, and rounds midpoint values to the nearest even number.

Does C# round up or down?

50000001" will always round up and ". 4999999" will always round down the the nearest integer. So a 15.5 can never become a 14. Any value that is larger than 14.5 and smaller than 15.5 will round to 15 any value larger than 15.5 and smaller than 16.5 will round to 16.

What is nullable decimal in C#?

Nullable Types are introduced in C#2.0, they allow you to assign null to a value type variable. In C#, You cannot assign null to a value type variable, if you write something like this i.e int x = null , then this will give compile time error.


2 Answers

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);
}
like image 200
dtb Avatar answered Sep 23 '22 11:09

dtb


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.

like image 31
Eric Lippert Avatar answered Sep 21 '22 11:09

Eric Lippert