Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

how do I get System.out.format to print out doubles with the same precision

872857Jul 2 2011 — edited Jul 5 2011
Using the System.out.format, how do I print out the value of a double such that it looks exactly like it does if it were print from a System.out.println.

For example, take the following code:
double d = 12.48564734342343;        
System.out.format("d as format: %f\n", d);
System.out.println("d as   sout: " + d);
Running the code, I get:
<font face="courier">
d as format: 12.485647
d as sout: 12.48564734342343
</font>

The precision of d has been lost.

I could bump up the precision as follows:
double d = 12.48564734342343;
System.out.format("d as format: %.14f\n", d);
System.out.println("d as   sout: " + d);
That appears to work, I get:
<font face="courier">
d as format: 12.48564734342343
d as sout: 12.48564734342343
</font>

However, that solution fails if d has a different precision, say 12.48. In that case I get:
<font face="courier">
d as format: 12.48000000000000
d as sout: 12.48
</font>

So how do I get System.out.format to print out doubles with the same precision as System.out.println?

Thanks..
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 2 2011
Added on Jul 2 2011
25 comments
565 views