File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Double to 3.s.f... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Double to 3.s.f..." Watch "Double to 3.s.f..." New topic
Author

Double to 3.s.f...

Andrew Hartman
Greenhorn

Joined: Mar 18, 2004
Posts: 16
Hi
How do you round a double to 3 significant figures?
Thanks
chi Lin
Ranch Hand

Joined: Aug 24, 2001
Posts: 348
double d1 = (int)(d1*1000)/1000.;
Nathaniel Stoddard
Ranch Hand

Joined: May 29, 2003
Posts: 1258
Well, first of all, we don't really just arbitrarily round values. We may display them to a certain number of significant digits when printed on the screen, but that's another story. The number itself is a certain number of bytes--and therefore a certain precision.
To print out a double formatted a specific way, use the java.text.DecimalFormat class. I think that will do what you want it to.
** Do you really want to round a double? Or just display it?
[ March 24, 2004: Message edited by: Nathaniel Stoddard ]

Nathaniel Stodard<br />SCJP, SCJD, SCWCD, SCBCD, SCDJWS, ICAD, ICSD, ICED
Herb Schildt
Author
Ranch Hand

Joined: Oct 01, 2003
Posts: 239
Andrew:
If you are using the new J2SE 1.5 beta, then there is a really easy way to display a double with three decimal places: use the new printf() method, which is defined by PrintStream.
There are many forms and features of printf() and a complete discussion is beyond the scope of this forum. (The J2SE 1.5 docs explains it fully.) However, to display a specific number of decimal places when outputing a double value, simply use a precision specifier, as the following program shows.

The output is:
10.124
Notice that printf( ) also rounds the output in the process.


For my latest books on Java, including my Java Programming Cookbook, see HerbSchildt.com
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Double to 3.s.f...