How to get an exception with inaccurate calculations?

Every time we need high decimal precision, we use decimal places to perform calculations. Is there a way to check if the accuracy is enough for the calculation?

I would like to make the following code for 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 really doesn't matter in real code, but it would be nice to be safe.

+5
source share
2 answers

This extension method should help. It cancels the operation and checks if the original arguments can be correctly calculated from the result. If this is not so, then the operation caused a loss of accuracy.

 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 regular operators like + , etc., you have to go with Philipp Schmid solution and implement the operators according to your decimal type.

+3
source

You can create a SaveDecimal class and overload the + operator https://msdn.microsoft.com/en-us/library/aa288467%28v=vs.71%29.aspx

 public class SafeDecimal { private decimal DecValue; public SafeDecimal(decimal Value) { DecValue = Value; } public decimal GetValue() { return DecValue; } public static SafeDecimal operator +(SafeDecimal A, SafeDecimal B) { decimal almostMax = Decimal.MaxValue - 1; checked { if (almostMax <= A.GetValue() + B.GetValue()) throw new Exception("----scary error message----"); } return new SafeDecimal(A.GetValue() + B.GetValue()); } } 
0
source

All Articles