use*_*759 12 java algorithm exception bigdecimal infinity
我在返回BigDecimal值的方法中编写算法,但现在计算的结果将是+或 - 无穷大.
而不是程序崩溃我想捕获异常并返回无穷大作为一个值,如果该方法返回双精度的方式.
例如Double.POSITIVE_INFINITY;
那么如何在BigDecimal中存储无穷大?还是有另一种方法吗?
public static BigDecimal myalgorithm(){
//code to store infinity in a BigDecimal
//return the BigDecimal holding infinity
}
Run Code Online (Sandbox Code Playgroud)
T.J*_*der 12
BigDecimal没有无限的概念.我可以想到三个选择:
该清洁方法可能是派生自己的MyBigDecimal类,添加无穷大标志,告诉你,如果实例包含无穷大,覆盖的方法,它是相关的(这将是他们中的大多数我想),使用基类的版本,当你没有持有无限和你自己的代码时.
您可以null在代码中使用标记值,尽管这可能有点痛苦.例如:
if (theBigDecimal == null) {
// It's infinity, deal with that
}
else {
// It's finite, deal with that
}
Run Code Online (Sandbox Code Playgroud)如果你已经在使用null其他东西,那么你可能有一个BigDecimal实际上并不包含无穷大的实例,但你假装它包含它,并用==它来检查它.例如:
// In your class somewhere:
static final BigDecimal INFINITE_BIG_DECIMAL = new BigDecimal(); // Value doesn't matter
// Then:
if (theBigDecimal == INFINITE_BIG_DECIMAL) {
// It's infinity, deal with that
}
else {
// It's finite, deal with that
}
Run Code Online (Sandbox Code Playgroud)