最近做 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.
* - Then decide if rounding up must be applied or not by following
* the half-even rounding rule, first using approximated scaled
* fractional part.
* - For the difficult cases (approximated scaled fractional part
* being exactly 0.5d), we refine the rounding decision by calling
* exactRoundUp utility method that both calculates the exact roundoff
* on the approximation and takes correct rounding decision.
* - We round-up the fractional part if needed, possibly propagating the
* rounding to integral part if we meet a "all-nine" case for the
* scaled fractional part.
* - We then collect digits from the resulting integral and fractional
* parts, also setting the required grouping chars on the fly.
* - Then we localize the collected digits if needed, and
* - Finally prepend/append prefix/suffix if any is needed.
*/
将传入的 double 数据拆分为整数部分和小数部分分别处理,根据半均匀四舍五入规则判断小数部分是否要进位;复杂情况比如近似值为0.5d时,将通过调用exactRoundUp方法改进求解近似值,该方法既计算了与近似值的差值也做了正确的近似值抉择;
如果碰到小数部分全是9的情况,我们会将小数部分进位到整数部分;最后拼接数字,设置分组字符,本地化,加前缀(如果有负号),返回字符串。