简体   繁体   中英

How can I 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 12.00 precision

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

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);

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 .

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

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(...) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM