[bug-62857] fix DOLLAR function

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1897719 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
PJ Fanning 2022-02-03 11:14:10 +00:00
parent 4690765436
commit 65048884d5
2 changed files with 16 additions and 4 deletions

View File

@ -20,8 +20,13 @@ package org.apache.poi.ss.formula.functions;
import static org.apache.poi.ss.formula.eval.ErrorEval.VALUE_INVALID;
import org.apache.poi.ss.formula.eval.*;
import org.apache.poi.util.LocaleUtil;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;
@ -93,6 +98,13 @@ public abstract class NumericFunction implements Function {
return VALUE_INVALID;
}
if (nPlaces < 0) {
BigDecimal divisor = BigDecimal.valueOf(Math.pow(10, -nPlaces));
BigInteger bigInt = BigDecimal.valueOf(val).divide(divisor, MathContext.DECIMAL128)
.toBigInteger().multiply(divisor.toBigInteger());
val = bigInt.doubleValue();
}
StringBuilder decimalPlacesFormat = new StringBuilder();
if (nPlaces > 0) {
decimalPlacesFormat.append('.');
@ -104,10 +116,11 @@ public abstract class NumericFunction implements Function {
decimalFormatString.append("$#,##0").append(decimalPlacesFormat)
.append(";($#,##0").append(decimalPlacesFormat).append(')');
DecimalFormat df = new DecimalFormat(decimalFormatString.toString());
DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(LocaleUtil.getUserLocale());
DecimalFormat df = new DecimalFormat(decimalFormatString.toString(), symbols);
return new StringEval(df.format(val));
}catch (EvaluationException e) {
} catch (EvaluationException e) {
return e.getErrorEval();
}
}

View File

@ -59,8 +59,7 @@ final class TestNumericFunction {
//https://support.microsoft.com/en-us/office/dollar-function-a6cd05d9-9740-4ad3-a469-8109d18ff611
assertString(fe, cell, "DOLLAR(1234.567,2)", "$1,234.57");
assertString(fe, cell, "DOLLAR(-1234.567,0)", "($1,235)");
//TODO need to fix code to handle next case
//assertString(fe, cell, "DOLLAR(-1234.567,-2)", "($1,200)");
assertString(fe, cell, "DOLLAR(-1234.567,-2)", "($1,200)");
assertString(fe, cell, "DOLLAR(-0.123,4)", "($0.1230)");
assertString(fe, cell, "DOLLAR(99.888)", "$99.89");
assertString(fe, cell, "DOLLAR(123456789.567,2)", "$123,456,789.57");