如何获得计算不准确的异常?
How to get an exception on inaccurate calculation?
每次我们需要很高的小数精度时,我们都会使用小数来进行计算。有什么方法可以检查精度是否足以进行计算?
我想让下面的代码抛出异常:
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.
在实际代码中这并不重要,但安全就好了。
您可以创建 SaveDecimal class 并重载 + 运算符
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());
}
}
这个扩展方法应该有所帮助。它反转操作并检查是否可以根据结果正确计算输入参数。如果不是这种情况,则操作会导致精度损失。
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;
}
工作示例:https://dotnetfiddle.net/vx6UYY
如果你想使用 +
等常规运算符,你必须使用 并在你自己的十进制类型上实现运算符。
每次我们需要很高的小数精度时,我们都会使用小数来进行计算。有什么方法可以检查精度是否足以进行计算?
我想让下面的代码抛出异常:
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.
在实际代码中这并不重要,但安全就好了。
您可以创建 SaveDecimal class 并重载 + 运算符
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());
}
}
这个扩展方法应该有所帮助。它反转操作并检查是否可以根据结果正确计算输入参数。如果不是这种情况,则操作会导致精度损失。
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;
}
工作示例:https://dotnetfiddle.net/vx6UYY
如果你想使用 +
等常规运算符,你必须使用