Meaningless Drivel is fun!
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

Double to 3.s.f...

Andrew Hartman

Joined: Mar 18, 2004
Posts: 16
How do you round a double to 3 significant figures?
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 ]

Herb Schildt
Ranch Hand

Joined: Oct 01, 2003
Posts: 253
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:
Notice that printf( ) also rounds the output in the process.

For my latest books on Java, including Introducing JavaFX 8 Programming, see
I agree. Here's the link:
subject: Double to 3.s.f...
It's not a secret anymore!