try to standardise big decimal code

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1899864 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
PJ Fanning 2022-04-14 17:01:51 +00:00
parent 6f50fb1bf7
commit 31cce15e22
1 changed files with 16 additions and 5 deletions

View File

@ -106,12 +106,21 @@ public class FractionFormat extends Format {
@SuppressWarnings("squid:S2111")
public String format(Number num) {
final double d = num.doubleValue();;
try {
//this is the recommended way (in BigDecimal javadocs to create a decimal from a double)
return format(new BigDecimal(Double.toString(d)));
} catch (NumberFormatException nfe) {
//Double.toString can fail
return format(d);
}
}
final BigDecimal doubleValue = new BigDecimal(num.doubleValue());
@SuppressWarnings("squid:S2111")
private String format(final BigDecimal decimal) {
final boolean isNeg = decimal.compareTo(BigDecimal.ZERO) < 0;
final boolean isNeg = doubleValue.compareTo(BigDecimal.ZERO) < 0;
final BigDecimal absValue = doubleValue.abs();
final BigDecimal absValue = decimal.abs();
final BigDecimal wholePart = new BigDecimal(absValue.toBigInteger());
final BigDecimal decPart = absValue.remainder(BigDecimal.ONE);
@ -148,7 +157,7 @@ public class FractionFormat extends Format {
}
} catch (RuntimeException e){
LOGGER.atWarn().withThrowable(e).log("Can't format fraction");
return Double.toString(doubleValue.doubleValue());
return Double.toString(decimal.doubleValue());
}
StringBuilder sb = new StringBuilder();
@ -184,10 +193,12 @@ public class FractionFormat extends Format {
return sb.toString();
}
@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
return toAppendTo.append(format((Number)obj));
}
@Override
public Object parseObject(String source, ParsePosition pos) {
throw new NotImplementedException("Reverse parsing not supported");
}