How can I convert String to Double without losing precision in Java?

后端 未结 4 1727
北恋
北恋 2020-12-18 07:05

Tried as below

String d=new String(\"12.00\");
Double dble =new Double(d.valueOf(d));
System.out.println(dble);

Output: 12.0

But i

4条回答
  •  一生所求
    2020-12-18 07:43

    Use BigDecimal Instead of a double:

    String d = "12.00"; // No need for `new String("12.00")` here
    BigDecimal decimal = new BigDecimal(d);
    

    This works because BigDecimal maintains a "precision," and the BigDecimal(String) constructor sets that from the number of digits to the right of the ., and uses it in toString. So if you just dump it out with System.out.println(decimal);, it prints out 12.00.

提交回复
热议问题