I want to round double? value, so if there is 2,3 should be 2 but if there is null then should be null.
Rounds a double-precision floating-point value to the nearest integral value, and rounds midpoint values to the nearest even number.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With