• Java POI读取excel中数值精度损失


    Java POI读取excel中数值精度损失

    描述:
    excel 单元格中,纯数字的单元格,读取后 后面会加上 .0 。
    例如: 1 --> 1.0

    而使用下面的方法,可能会对小数存在精度损失

    cell.setCellType(CellType.STRING); //读取前将单元格设置为文本类型读取
    

    例如: 2.2 --> 2.1999999997

    目前的解决办法:
    一. 将excel单元格改为文本类型。
    注意,直接修改单元格属性不管用, 使用 分列 的方式,可以实现将数值改为文本类型。

    二. java处理

    public class CommonUtil {
    
        private static NumberFormat numberFormat = NumberFormat.getNumberInstance();
    
        static {
            numberFormat.setGroupingUsed(false);
        }
    
        public static String getCellValue(Cell cell) {
            if (null == cell) {
                return "";
            }
            Object value;
            switch (cell.getCellTypeEnum()) {
                // 省略
                case NUMERIC:
                    double d = cell.getNumericCellValue();   
                    value = numberFormat.format(d);        // 关键在这里!
                //省略 
            }
            return value == null ? "" : value.toString();
        }
    }
    

    上面的方法可以获取一个正确的数值

    参考

  • 相关阅读:
    centos7.5部署mysql cluster NDB总结
    读《构建之法》13--17章有感
    读《构建之法》8--10章
    作业5.2
    作业5.1
    读《构建之法》6--7章读后感
    做汉堡,做汉堡
    《构建之法》1—5章读后感
    第二次作业
    1
  • 原文地址:https://www.cnblogs.com/magicya/p/12626377.html
Copyright © 2020-2023  润新知