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

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 want to get accuracy 12.00

please let me know the correct path without using the format () method in the string class

+4
source share
4 answers

Use BigDecimal Instead of double:

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

This works because BigDecimal supports "precision", and the BigDecimal(String) constructor sets which of the digits to the right of . , and uses it in toString . Therefore, if you just throw it System.out.println(decimal); with System.out.println(decimal); , he displays 12.00 .

+7
source

Your problem is not a loss of accuracy, but the output format of your number and its number of decimal places. 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, point:

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

Then by declaring your DecimalFormat :

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

You have not lost accuracy; 12.0 is exactly 12.00. If you want to display or print it with two decimal places, use java.text.DecimalFormat

+2
source

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

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

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

UPDATE:

If you do not want to use PrintStream#format(...) , use DecimalFormat#format(...) .

+1
source

All Articles