java - 如何准确的将科学计数法表示的Double类型转换为正常的字符串?

 奔跑的蜗牛彡 发布于 2022-10-25 11:09

1.起因

 最近在做Excel解析,要知道,在Excel中会将长数字自动转换为科学计数法表示,我的问题是如何原样
 读取出来并用字符串表示,为了方便说明,我新建一个Workbook,在第一个Sheet的第一个Cell中填入:
 123456729.326666,Excel中显示为:

现在我需要利用POI将其读取出来,并原样打印:123456729.326666。

2.我的代码如下:

public static void main(String[] args) throws FileNotFoundException, IOException {
        String filePath="C:/Users/yan/Desktop/testDouble.xlsx";
        File file = null;
        InputStream is = null;
        try {
            file=new File(filePath);
            is = new FileInputStream(file);
            XSSFWorkbook workbook = new XSSFWorkbook(is);
            XSSFCell cell1 = workbook.getSheetAt(0).getRow(0).getCell(0);
            //获取double类型的值
            Double d = cell1.getNumericCellValue();
            System.err.println("科学计数法表示:\n\t"+d);//此时打印出来是科学计数法
            /**
             * 使用NumberFormat转换
             */
            NumberFormat nf = NumberFormat.getInstance();
            String s = nf.format(d);
            System.err.println("经过NumberFormat格式化后:\n\t"+s);
            /**
             * 使用DecimalFormat转换字符串
             */
            DecimalFormat df = new DecimalFormat();
            s=df.format(d);
            System.err.println("经过DecimalFormat格式化后:\n\t"+s);
            /**
             * 直接使用BigDecimal表示
             */
            BigDecimal bd = new BigDecimal(d);
            //转换为工程??我也不知道怎么称呼
            s = bd.toEngineeringString();
            System.err.println("toEngineeringString表示:\n\t" + s);
            //使用网上普遍的解决办法toPlainString
            s = bd.toPlainString();
            System.err.println("toPlainString表示:\n\t" + s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

输出结果

疑问

可以看到,我并没有得到想要的结果(123456729.326666),使用*Format之后只保留3位小数,此处不设置#.####等格式是因为并不确定输入的小数可以达到多少位,继而使用了网上推荐的toPlainString方法得到的结果也并不精确,求各位大神指点。

2 个回答
  • double 本身就存在精度问题,可以用BigDecimal再转换一下,指定一下小数点位数再输出:

    /**
     * 转换数值为指定位数
     * @param value 原始数值的字符串表示形式
     * @param scale 保留小数点位数
     * @return 转换后的字符串
     */
    public static String toStandardString(String value, int scale) {
        return new BigDecimal(value).setScale(scale, BigDecimal.ROUND_HALF_UP).toEngineeringString();
    }
    
    

    toStandardString("123456729.32666599750518798828125", 6);// 输出为123456729.3266666

    2022-10-26 23:23 回答
  • 自问自答:使用cell.getNumericCellValue()得到double数据再转换成字符串doubleStr,当doubleStr.contains("E")为真时调用一下方法:

    private static String getRealNumOfScientificNotation(String doubleStr) {
            int indexOfE = doubleStr.indexOf('E');
            int indexOfPoint = doubleStr.indexOf('.');
            // 整数部分
            BigInteger zs = new BigInteger(doubleStr.substring(0, indexOfPoint));
            // 小数部分
            BigInteger xs = new BigInteger(doubleStr.substring(indexOfPoint
                    + BigInteger.ONE.intValue(), indexOfE));
            // 指数
            int pow = Integer.valueOf(doubleStr.substring(indexOfE
                    + BigInteger.ONE.intValue()));
            StringBuffer buffer = new StringBuffer();
            // e.g. 1.23E-5
            if (pow < 0) {
                for (int i = 0; i < -pow; i++) {
                    buffer.append(0);
                }
                buffer.insert(BigInteger.ONE.intValue(), ".");
                buffer.append(zs.toString()).append(xs.toString());
                doubleStr = buffer.toString();
            } else {
                int xsLen = xs.toByteArray().length;
                int needFill0 = pow - xsLen;
                if (needFill0 < 0) {
                    // e.g. 1.234E2
                    buffer.append(xs);
                    buffer.insert(pow, ".");
                    buffer.insert(0, zs);
                    doubleStr = buffer.toString();
                } else {
                    // e.g. 1.234E6 or 1.234E3
                    for (int i = 0; i < needFill0; i++) {
                        buffer.append(0);
                    }
                    buffer.insert(0, xs);
                    buffer.insert(0, zs);
                    doubleStr = buffer.toString();
                }
            }
            return doubleStr;
        }
    2022-10-26 23:23 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有