Join
Blogs
Questions
Videos
Tags
Members
Search
 
 
Create your own blog, earn points and get popular!

Preserving the Precision Value of a double

I have a double variable

double d = 4.24

When i convert this into a String I lose the precision Value and it returns back 4.2.

I know we could achieve this using Decimal format .... but is there any other way of achieving this.

No votes yet
Share this
2 answers
Sameera's picture
I do not think loss of precision should happen for only 2 decimals. A quick program shows that it works perfectly. 
  1. double d = 2.34;
  2. String str = String.valueOf(d);
  3. System.out.println(str);
  4. double d1 = Double.parseDouble(str);
  5. System.out.println(d1);

will print
2.34
2.34

How are you converting double to String and back?
In addition, if you are looking for precise decimal values, you should use BigDecimal instead of double.
No votes yet
Ramnath's picture
thank you for the code , but if I get a double d = 2.30 then System.out.println(str); --> would be 2.3 and "0" would be lost. I do agree your thoughts for using Big Decimal , but as i was maitaining Legacy Code , it was not possible at this juncture.
No votes yet