From 31cce15e224b1b2df9cd1b4ed4aac17e3976f303 Mon Sep 17 00:00:00 2001 From: PJ Fanning Date: Thu, 14 Apr 2022 17:01:51 +0000 Subject: [PATCH] try to standardise big decimal code git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1899864 13f79535-47bb-0310-9956-ffa450edef68 --- .../poi/ss/usermodel/FractionFormat.java | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/poi/src/main/java/org/apache/poi/ss/usermodel/FractionFormat.java b/poi/src/main/java/org/apache/poi/ss/usermodel/FractionFormat.java index 3e528f986a..f5ffd91faf 100644 --- a/poi/src/main/java/org/apache/poi/ss/usermodel/FractionFormat.java +++ b/poi/src/main/java/org/apache/poi/ss/usermodel/FractionFormat.java @@ -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"); }