有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将字符串转换为不带科学符号的双精度

我在网上搜索过,但找不到任何解决方案(也许,我搜索得不好)
我想把String"108595000.5"转换成double,我使用了以下方法:

Double.parseDouble("108595000.5");
Double.valueOf("108595000.5");

不幸的是,它们都返回1.08595E8
我怎样才能毫无问题地将这个String转换成double


共 (2) 个答案

  1. # 1 楼答案

    您使用的方法不会返回1.08595E8,而是返回数字,您抱怨的是控制台中该数字的表示(或作为String

    但是,您可以指定如何使用指定的格式输出double,请参见以下示例:

    public static void main(String[] args) {
        String value = "108595000.5";
        // use a BigDecimal to parse the value
        BigDecimal bd = new BigDecimal(value);
        // choose your desired output:
        // either the String representation of a double (undesired)
        System.out.println("double:\t\t\t\t\t" + bd.doubleValue());
        // or an engineering String
        System.out.println("engineering:\t\t\t\t" + bd.toEngineeringString());
        // or a plain String (might look equal to the engineering String)
        System.out.println("plain:\t\t\t\t\t" + bd.toPlainString());
        // or you specify an amount of decimals plus a rounding mode yourself
        System.out.println("rounded with fix decimal places:\t" 
                            + bd.setScale(2, BigDecimal.ROUND_HALF_UP));
    }
    
    double:                             1.085950005E8
    engineering:                        108595000.5
    plain:                              108595000.5
    rounded with fix decimal places:    108595000.50
    
  2. # 2 楼答案

    尝试使用

    value = new BigDecimal(yourString);
    doubleValue = value.doubleValue();
    

    如果您想要精确的值

    如果你想在","后面加两个数字

    double a = yourDouble; 
    System.out.printf("%.2f",a)