rounding a double

Hi all,as you can tell from my question I am new to JAVA. So far I love it.I need to round a double to 2 places but the Math.round method rounds to an integer. Does someone have a good way to round to 2 places? ThanksMessage was edited by: LTLhawk
[289 byte] By [LTLhawka] at [2007-11-27 2:02:01]
# 1
Do you want a String where the double is formatted to two decimal places,or do you want a double variable that holds a rounded value?
DrLaszloJamfa at 2007-7-12 1:42:52 > top of Java-index,Java Essentials,New To Java...
# 2
well, I would love to see both, but for this project I just need a string that will be formatted to hold the double to 2 placesMessage was edited by: LTLhawk
LTLhawka at 2007-7-12 1:42:52 > top of Java-index,Java Essentials,New To Java...
# 3
> well, I would love to see both, but for this project. I just need a string > that will be formatted to hold the double to 2 placesHave a look at the DecimalFormat class.kind regards,Jos
JosAHa at 2007-7-12 1:42:52 > top of Java-index,Java Essentials,New To Java...
# 4

You can use NumberFormat:

import java.text.*;

public class RoundedExample {

public static void main(String[] args) {

double x = 1.235;

NumberFormat fmt = NumberFormat.getNumberInstance();

fmt.setMinimumFractionDigits(2);

fmt.setMaximumFractionDigits(2);

String s = fmt.format(x);

System.out.println(s);

}

}

There is also double formatting capabilities built into java.util.Formatter

and the format method of java.io.PrintWriter/PrintStream.

DrLaszloJamfa at 2007-7-12 1:42:52 > top of Java-index,Java Essentials,New To Java...
# 5
I researched that NumberFormat and it worked great..I will look into the othr examples to... thanks guys. I really appreciate your help
LTLhawka at 2007-7-12 1:42:52 > top of Java-index,Java Essentials,New To Java...
# 6
> You can use NumberFormat:I usually prefer a simple DecimalFormat here:DecimalFormat df= new DecimalFormat("#.00");...System.out.println(df.format(1234.5678));kind regards,Jos
JosAHa at 2007-7-12 1:42:52 > top of Java-index,Java Essentials,New To Java...