Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Double to 3.s.f...

 
Andrew Hartman
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
How do you round a double to 3 significant figures?
Thanks
 
chi Lin
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
double d1 = (int)(d1*1000)/1000.;
 
Nathaniel Stoddard
Ranch Hand
Posts: 1258
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Author
Ranch Hand
Posts: 253
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic