-3

Possible Duplicate:
Round to 2 decimal places

Suppose in a variable i have a decimal number like 3.1426384473 but i want 3.14. now how i can format decimal numbers up to two decimals points like in above example.

Community
  • 1
  • 1
John
  • 13
  • 1
  • 5
  • You can do that with a [DecimalFormatter](http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html) – ChadNC May 15 '12 at 10:57

3 Answers3

3

double pi=3.1426384473;

System.out.printf("%.2f",pi);

Mohamed Jameel
  • 602
  • 5
  • 21
1

try this....

DecimalFormat df = new DecimalFormat("#.##");
df.format(3.1426384473);

Or if u just wanna print then u can use this also...

System.out.printf("%.2f",d); //d is your number
Addicted
  • 1,694
  • 1
  • 16
  • 24
0
public static double round(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    long factor = (long) Math.pow(10, places);
    value = value * factor;
    long tmp = Math.round(value);
    return (double) tmp / factor;
}
aviad
  • 8,229
  • 9
  • 50
  • 98