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

后端 未结 4 1737
北恋
北恋 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:56

    Your problem is not a loss of precision, but the output format of your number and its number of decimals. You can use DecimalFormat to solve your problem.

    DecimalFormat formatter = new DecimalFormat("#0.00");
    String d = new String("12.00");
    Double dble = new Double(d.valueOf(d));
    System.out.println(formatter.format(dble));
    

    I will also add that you can use DecimalFormatSymbols to choose which decimal separator to use. For example, a point :

    DecimalFormatSymbols separator = new DecimalFormatSymbols();
    separator.setDecimalSeparator('.');
    

    Then, while declaring your DecimalFormat :

    DecimalFormat formatter = new DecimalFormat("#0.00", separator);
    

提交回复
热议问题