Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an exception on inaccurate calculation?

Every time we need a high decimal-precision, we use decimals to do the calculations. Is there any way to check if the precision did suffice for the calculation?

I would like to make the following code throw an exception:

decimal almostMax = Decimal.MaxValue - 1;
decimal x = almostMax + 0.1m; // This should create an exception, since x equals almostMax.
Assert.AreEqual(x, almostMax); // This does NOT fail.

It doesn't really matter in real code, but it would be nice to be safe.

like image 425
Andreas Avatar asked Oct 19 '22 03:10

Andreas


1 Answers

This extension method should help. It reverses the operation and checks if the input arguments can be calculated correctly from the result. If that's not the case then the operation caused precision loss.

public static decimal Add(this decimal a, decimal b)
{
    var result = a + b;

    if (result - a != b || result - b != a)
        throw new InvalidOperationException("Precision loss!");

    return result;
}

Working example: https://dotnetfiddle.net/vx6UYY

If you want to use the regular operators like + etc, you have to go with Philipp Schmid's solution and implement the operators on your own decimal type.

like image 175
Good Night Nerd Pride Avatar answered Nov 01 '22 10:11

Good Night Nerd Pride