I'm working on a project which requires me to have double values at exactly 2 decimal place. Using some math, I currently have most numbers rounded correctly, except if there are trailing zeros. I want to keep these 0's for results like 0.00 in particular This list is displayed in a TableView, so therefore must be sortable numerically. I'd like the double values to actually be doubles so that it may properly sort.
Is there any way I can keep 2 decimal places without String.format?
Thank you in advance.
You can use DecimalFormat
DecimalFormat df = new DecimalFormat("#.00");
00
= exactly two decimal places.
But this will give to you a String
that you can convert again to a double
, if you don't want to have this String-conversion
check this question to see how it can be achieved using BigDecimal
.
IMHO, if this is not for learning pourposes DecimalFormat
will be enough for you. True, you will have to use String
in some moment of the conversion, but you will only read and store double
values and your sorting will be the correct...
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With