• Post Reply Bookmark Topic Watch Topic
  • New Topic

rounding a value  RSS feed

 
william brown
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Let say I hava a value 245.678909. I want to display it as 245.68. It is a double value. What should I do?

Thank you.
 
Norm Radder
Ranch Foreman
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is probably a Java class to do that. It might be called DecimalFormat.
See also NumberFormat.
Read the doc on that and do a search on some of these forums for sample code to use it.
 
Rick O'Shay
Ranch Hand
Posts: 531
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
double value = 123.456789;
...
System.out.print( String.format("%3.2f", value) );
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rick solution is only available in Java 5, in case you can't find String.format in your javadocs. In that case, go with DecimalFormat.
 
Rick O'Shay
Ranch Hand
Posts: 531
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ulf Dittmer:
Rick solution is only available in Java 5, in case you can't find String.format in your javadocs. In that case, go with DecimalFormat.


It's been out for a year plus so I'm assuming 5.0 unless otherwise stated.
 
Andrew Morris
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
make a java.text.DecimalFormat like:
static DecimalFormat df=new DecimalFormat("0.00");
use
System.out.println(df.format(aDoubleValue));
and it does the rounding.

-------------------
Andrew Morris
www.devsquare.com
DevSquare - Online Application Development
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!