最近做 Excel 导入功能的时候遇到了计算精度的问题。直接导入单元格数据问题不大,但是碰到有计算公式的单元格,在加减乘除之后就效果感人。例如尝试计算 34*1.1445 得到的结果为 38.913000000000004。查看公式处理方法formulaEvaluator.evaluate(cell).getNumberValue() 中 接口 FormulaEvaluator 的方法 evaluate(Cell cell) 的实现类为 HSSFFormulaEvaluator, 方法的实质是创建 CellValue 对象,其中 numberValue 属性为 double 类型就导致计算的过程存在精度问题。
知道原因后,解决方法就简单了,可以对计算结果进行格式化,调用 numberFormat.format(formulaEvaluator.evaluate(cell).getNumberValue())
如此就有些好奇格式化具体是如何实现的,主要方法调用链为
java.text.NumberFormat.format(double number)->java.text.DecimalFormat.fastFormat(double d)->java.text.DecimalFormat.fastDoubleFormat(double d, boolean negative)
所以直接看 fastDoubleFormat 方法即可
/*
* The principle of the algorithm is to :
* - Break the passed double into its integral and fractional parts
* converted into integers.
&nbs