Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is a better way to convert 5.6789 to 5.68?

 
Chris Ben
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
the question is as my topic. I know there are a lot methods to do that in Java, but is there any class in Java which can directly do this format conversion?
Thanks a lot
Chris
 
Jody Seigle
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The DecimalFormat class in the java.text package

double d = 5.6789;
DecimalFormat df = new DecimalFormat(0.00);
String output = df.format(d); // <- equals "5.68"
check the API for the description of the possible output formats.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

You could multiply by 100.
Do a Math.round();
Divide by 100.
 
Chris Ben
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks.
 
Yogen Vadnere
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I already posted following code in one of the forum,
import java.util.* ;
import java.text.* ;
public class test{
public static void main(String s[]){
double formatDouble = 750.1234 ;
NumberFormat converter = NumberFormat.getInstance() ;
converter.setMaximumFractionDigits(2);
converter.setMinimumFractionDigits(2);
System.out.println(converter.format(formatDouble));
}
}
 
Chris Ben
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is always nice to know more.
Thank you
Chris
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic