EasyExcel导入小数转BigDecimal精度问题

EasyExcel使用说明,点击链接https://www.yuque.com/easyexcel/doc/read

转Double也可参考该博客

最近使用easyexcel时碰到一个这样的问题,读取excel时出现了小数点精度问题。例如,0.137这个值,使用easyexcel解析后得到的Double对象就变成了0.13700000000000001,5.1,变成5.0999999999999996。

原excel中一条数据,见下图体积

商品名称长(cm)宽(cm)高(cm)体积(cm³)重量(Kg)
按摩油5.14.011.6236.640.137

实体类

 

**
 * 商品主数据
 *
 * @author yk
 * @Date 2020-02-26
 */
@Data
public class GoodsTempImportVo {


    @ExcelProperty(value = "商品名称")
    private String goodsName;

    @ExcelProperty(value = "长(cm)")
    private BigDecimal length;

    @ExcelProperty(value = "宽(cm)")
    private BigDecimal width;

    @ExcelProperty(value = "高(cm)")
    private BigDecimal height;

    @ExcelProperty(value = "体积(cm³)")
    private BigDecimal volume;

    @ExcelProperty(value = "重量(Kg)")
    private BigDecimal weight;


}

通过接口导入,打印出数据格式

解析到一条数据:{"goodsName":"按摩油","height":11.6,"length":5.0999999999999996,"volume":236.64,"weight":0.13700000000000001,"width":4}

 

我尝试去查看了excel解压后的文件,发现这条数据在xml里存储的值就是0.13700000000000001。

当我在把实体类里把BigDecimal的字段修改成String类型后,读出来的数据就是期望的0.137。

查看easyexcel源码,其实easyexcel解析excel单元格的时候,会根据单元格格式选择不同的converter。在本例中,由于是数字类型单元格解析成BigDecimal类型字段,调用的就是BigDecimalNumberConverter 。这个Converter是这样的:

public class BigDecimalNumberConverter implements Converter<BigDecimal> {
    public BigDecimalNumberConverter() {
    }

    public Class supportJavaTypeKey() {
        return BigDecimal.class;
    }

    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.NUMBER;
    }

    public BigDecimal convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        return cellData.getNumberValue();
    }

    public CellData convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        return new CellData(value);
    }
}

supportJavaTypeKey方法指定该Converter转换的目标类型是BigDecimal,而easyexcel在讲excel单元格内容转换为BigDecimal时调用的就是convertToJavaData方法。

可以看到该方法内容很简单,就是取了CellData的NumberValue,这是个BigDecimal的对象,debug时会发现,执行到这里时取出来的就已经是0.13700000000000001这个值了。

这没有问题,因为excel文件里存储的本来就是这个值,但是为什么转换成String类型就是0.137呢?

数字类型单元格转换成String类型调用的是另外一个converter:StringNumberConverter,可以看到这个类的convertToJavaData就更复杂一些:

public class StringNumberConverter implements Converter<String> {
    public StringNumberConverter() {
    }

    public Class supportJavaTypeKey() {
        return String.class;
    }

    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.NUMBER;
    }

    public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        if (contentProperty != null && contentProperty.getDateTimeFormatProperty() != null) {
            return DateUtils.format(DateUtil.getJavaDate(cellData.getNumberValue().doubleValue(), contentProperty.getDateTimeFormatProperty().getUse1904windowing(), (TimeZone)null), contentProperty.getDateTimeFormatProperty().getFormat());
        } else if (contentProperty != null && contentProperty.getNumberFormatProperty() != null) {
            return NumberUtils.format(cellData.getNumberValue(), contentProperty);
        } else if (cellData.getDataFormat() != null) {
            return DateUtil.isADateFormat(cellData.getDataFormat(), cellData.getDataFormatString()) ? DateUtils.format(DateUtil.getJavaDate(cellData.getNumberValue().doubleValue(), globalConfiguration.getUse1904windowing(), (TimeZone)null)) : NumberUtils.format(cellData.getNumberValue(), contentProperty);
        } else {
            return NumberUtils.format(cellData.getNumberValue(), contentProperty);
        }
    }

    public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        return new CellData(new BigDecimal(value));
    }
}

本例中的单元格格式为常规,所以调用的是NumberUtils的format方法,最后是通过ExcelGeneralNumberFormat类的format方法进行的处理。

在这个方法中,我们发现它将excel里解析出的值限制为10位小数,并且做了四舍五入的处理:


// Non-integers of non-scientific magnitude are formatted as "up to 11
// numeric characters, with the decimal point counting as a numeric
// character". We know there is a decimal point, so limit to 10 digits.
// https://support.microsoft.com/en-us/kb/65903
final double rounded = new BigDecimal(value).round(TO_10_SF).doubleValue();
return decimalFormat.format(rounded, toAppendTo, pos);

于是0.13700000000000001经过处理后就变成了0.137。

现在我们有了一个解决这个问题的办法,就是在easyexcel解析生成对象后,对每个BigDecimal字段做一样的处理:

new BigDecimal(value).round(new MathContext(10, RoundingMode.HALF_UP)).doubleValue();

最终整合出一个小方法,仅供参考:

 private void convertBigDecimal(Object object) {
        try {
            Field[] field = object.getClass().getDeclaredFields();
            for (int j = 0; j < field.length; j++) {
                String type = field[j].getGenericType().toString();
                if (type.equals("class java.math.BigDecimal")) {
                    try {
                        String name = field[j].getName();
                        name = name.substring(0, 1).toUpperCase() + name.substring(1);
                        Method getM = object.getClass().getMethod("get" + name);
                        BigDecimal value = (BigDecimal) getM.invoke(object);
                        if (Objects.nonNull(value) && value.compareTo(BigDecimal.ZERO) > 0) {
                            double newValue = value.round(new MathContext(10, RoundingMode.HALF_UP)).doubleValue();
                            Method setM = object.getClass().getMethod("set" + name, BigDecimal.class);
                            setM.invoke(object, BigDecimal.valueOf(newValue));
                        }
                    } catch (NoSuchMethodException e) {
                        LOGGER.error("转换错误 error ", e);
                    } catch (IllegalAccessException e) {
                        LOGGER.error("转换错误 error ", e);
                    } catch (InvocationTargetException e) {
                        LOGGER.error("转换错误 error ", e);
                    }
                }
            }
        } catch (RuntimeException e) {
            LOGGER.error("转换错误 error ", e);
        }
    }

这样我们通过解析得到的数据,基本上就和你在office/wps软件上看到的数值一致了。


 

  • 10
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值