From 7f56717398cde0d8e26155fed4909353332ba64d Mon Sep 17 00:00:00 2001 From: YUFEIFUT <55017929+YUFEIFUT@users.noreply.github.com> Date: Mon, 1 Jul 2024 13:44:24 +0800 Subject: [PATCH] Fix the rounding issue for numeric type formatting Resolve the current issue with the DecimalFormat class when the incoming obj is of type Double or Float. For example, if a Double type value of 1.005 is passed in, and the corresponding cell in Excel is of numeric type and set to keep two decimal places. Formatting the Double value 1.005 will be problematic; it will be formatted as 1.00, which is inconsistent with the behavior of Excel and does not perform rounding correctly --- .../java/org/apache/poi/ss/usermodel/DataFormatter.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/poi/src/main/java/org/apache/poi/ss/usermodel/DataFormatter.java b/poi/src/main/java/org/apache/poi/ss/usermodel/DataFormatter.java index f94e6893f7a..fe201574878 100644 --- a/poi/src/main/java/org/apache/poi/ss/usermodel/DataFormatter.java +++ b/poi/src/main/java/org/apache/poi/ss/usermodel/DataFormatter.java @@ -823,6 +823,14 @@ private Object scaleInput(Object obj) { @Override public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { obj = scaleInput(obj); + // Resolve the current issue with the DecimalFormat class when the incoming obj is of type Double or Float + // For example, if a Double type value of 1.005 is passed in, and the corresponding cell in Excel is of numeric type + // and set to keep two decimal places + // Formatting the Double value 1.005 will be problematic; it will be formatted as 1.00, which is inconsistent with + // the behavior of Excel and does not perform rounding correctly + if (obj instanceof Double || obj instanceof Float) { + return df.format(new BigDecimal(obj.toString()), toAppendTo, pos); + } return df.format(obj, toAppendTo, pos); }