2

Possible Duplicate:
Round a double to 2 significant figures after decimal point

The code below works

import java.text.DecimalFormat;

public class Test {
public static void main(String[] args){

    double x = roundTwoDecimals(35.0000);
    System.out.println(x);
}

public static double roundTwoDecimals(double d) {   
    DecimalFormat twoDForm = new DecimalFormat("#.00");
    twoDForm.setMinimumFractionDigits(2);
    return Double.valueOf(twoDForm.format(d));
}
}

it results to 35.0. How to forced the minimum number of decimal places? The output I want is 35.00

Community
  • 1
  • 1
JR Galia
  • 16,343
  • 19
  • 84
  • 143

2 Answers2

4

This isn't working like you expect because the return value of roundTwoDecimals() is of type double, which discards the formatting you do within the function. In order to achieve what you want, you might consider returning the String representation from roundTwoDecimals() instead.

VeeArr
  • 5,716
  • 2
  • 19
  • 44
0

Converting formatted number back to double will make you lose all formatting changes. Change the function to:

public static String roundTwoDecimals(double d) {   
    DecimalFormat twoDForm = new DecimalFormat("#.00");
    return twoDForm.format(d);
}

EDIT: you were right, "#.00" is correct.

Jakub Zaverka
  • 8,574
  • 3
  • 28
  • 47
  • Actually, `#.##` would make the decimal places optional, which doesn't seem to be what he wants. The advice about returning the `String` is the relevant part. – VeeArr Mar 19 '12 at 20:21