easyexcel 数字类型读取,精度与无效小数问题

kpbwa7wx  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(57)

功能需求:限制用户输入小数位数
异常场景举例:xlsx文件,限制最大输入4位小数,用户输入4.6,最后读取的值为4.60000000000000,导致有效输入校验失败
场景复现:
easyexcel版本:3.3.2
源输入:

POI读取:4.5999999999999996
easyexcel转换后(tempCellData.getOriginalNumberValue().round(EasyExcelConstants.EXCEL_MATH_CONTEXT))):4.60000000000000
临时解决方案,自定义数字转换去掉无意义的0:
public static class CustomNumberConverter implements Converter {
@OverRide
public Class<?> supportJavaTypeKey() {
return BigDecimal.class;
}

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

    @Override
    public BigDecimal convertToJavaData(ReadConverterContext<?> context) throws Exception {
        return context.getReadCellData().getNumberValue().stripTrailingZeros();
    }

    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<BigDecimal> context) throws Exception {
        return Converter.super.convertToExcelData(context);
    }
}

我想问下有什么方法能源头解决读取到的精度就不丢失吗?
cmssoen2

cmssoen21#

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.read.context.ReadConverterContext;
import com.alibaba.excel.write.context.WriteCellData;
import com.alibaba.excel.write.context.WriteConverterContext;

import java.math.BigDecimal;

public class CustomNumberConverter implements Converter<BigDecimal> {

    @Override
    public Class<BigDecimal> supportJavaTypeKey() {
        return BigDecimal.class;
    }

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

    @Override
    public BigDecimal convertToJavaData(ReadConverterContext context) throws Exception {
        // Use BigDecimal to retain precision
        // Convert the numeric value to BigDecimal and return
        return new BigDecimal(context.getReadCellData().getStringValue());
    }

    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<BigDecimal> context) throws Exception {
        // Convert BigDecimal back to numeric value for writing to Excel
        return new WriteCellData<>(context.getOriginalFieldValue().toPlainString(), CellDataTypeEnum.STRING);
    }
}

相关问题