java - 如何准确的将科学计数法表示的Double类型转换为正常的字符串?
大家讲道理
大家讲道理 2017-04-18 10:52:02
0
2
1576

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方法得到的结果也并不精确,求各位大神指点。

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

répondre à tous(2)
阿神

Auto-question et réponse : utilisez cell.getNumericCellValue() pour obtenir des données doubles et les convertir en chaîne doubleStr. Lorsque doubleStr.contains("E") est vrai, appelez la méthode :

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;
    }
迷茫

Double lui-même a des problèmes de précision. Vous pouvez utiliser BigDecimal pour le convertir à nouveau, spécifier le nombre de points décimaux, puis afficher :

/**
 * 转换数值为指定位数
 * @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);//La sortie est 123456729.3266666

Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!