This answer expands on the suggestion to use java.math.BigDecimal rather than double.
It is better for this application than double because every two decimal place number is exactly representable in BigDecimal. The rounding from an arbitrary double-representable value down to two decimal places can be easily done according to any of several rounding modes, including the one used for double arithmetic.
On the other hand, it is better than String because the natural sort order is numeric value.
Here is a short demo program illustrating these points:
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Test {
public static void main(String[] args) throws Throwable {
List<BigDecimal> list = new ArrayList<BigDecimal>();
double[] in = {
3.5,
Math.PI,
-100.123456,
1e6
};
System.out.println("Original doubles: "+Arrays.toString(in));
for(double d : in){
list.add(doubleToBigDecimal(d,1));
}
System.out.println("Before sorting: " + list);
Collections.sort(list);
System.out.println("After sorting: " + list);
}
public static BigDecimal doubleToBigDecimal(double in, int places) {
BigDecimal result = new BigDecimal(in).setScale(2,
BigDecimal.ROUND_HALF_EVEN);
return result;
}
}
Output:
Original doubles: [3.5, 3.141592653589793, -100.123456, 1000000.0]
Before sorting: [3.50, 3.14, -100.12, 1000000.00]
After sorting: [-100.12, 3.14, 3.50, 1000000.00]