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

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

    You have not lost any precision, 12.0 is exactly equal to 12.00. If you want to display or print it with 2 decimal places, use java.text.DecimalFormat

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-12-18 08:07

    If you want to format output, use PrintStream#format(...):

    System.out.format("%.2f%n", dble);
    

    There %.2f - two places after decimal point and %n - newline character.

    UPDATE:

    If you don't want to use PrintStream#format(...), use DecimalFormat#format(...).

    0 讨论(0)
提交回复
热议问题