以下是 Excel 中有效的自定义数字格式:#,##0.0,
请注意末尾的逗号。它允许 Excel 将数字缩小 1000;
同样,末尾的双逗号将数字缩小百万。
但是,在Java中,当我创建此格式时使用DecimalFormat(如下代码所示,它会抛出异常并显示消息:格式错误的模式 "#,##0.0,"
String format="#,##0.0,";
DecimalFormat df = new DecimalFormat(format);
有什么方法可以创建这个 DecimalFormat 来执行缩小操作吗?
例如,如果我在 Excel 中将相同的模式应用于数字 705.0,则 Excel 中显示的结果为 0.7
这就是我期望执行后的输出:
String result = df.format(new Double(705.0));
如果没有办法,我希望在应用格式之前手动除以1000来获得结果:#,##0.0
最佳答案
解决这个问题的简单方法是创建您自己的 NumberFormat 子类,该子类在内部使用 DecimalFormat,但也跟踪那些结尾逗号。类似的东西
public class ExcelFormat extends NumberFormat {
private DecimalFormat df;
private int endingCommas;
public ExcelFormat(String format) {
//calculate the ending commas. Remove from format
//create df using the substring with the commas removed
}
public String format(double number, StringBuffer buf, FieldPosition fp) {
//divide the number by what's indicated by the endingCommas
return df.format(adjustedNumber);
}
}
关于java - 带有尾随逗号的有效 Excel 自定义数字被 DecimalFormat 视为格式错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58124386/