user1938073
user1938073

Reputation: 121

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

Upvotes: 5

Views: 17923

Answers (4)

PermGenError
PermGenError

Reputation: 46408

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.

Upvotes: 8

Rob
Rob

Reputation: 15982

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

Upvotes: 8

bsiamionau
bsiamionau

Reputation: 8229

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

Upvotes: 1

jalynn2
jalynn2

Reputation: 6457

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

Upvotes: 2

Related Questions