I want to round my double value down to N decimal places (say, one), esentially just leaving out all the digits that follow:
0.123 #=> 0.1
0.19 #=> 0.1
0.2 #=> 0.2
This question has been brought up numerous times, for example here and here. The recommended approach is to use BigDecimal
and then scale it, in particular to avoid expensive converting to string and back. The rounding mode I need is apparently RoundingMode.DOWN
.
So the method is something like this:
static double truncate(double value, int places) {
return new BigDecimal(value)
.setScale(places, RoundingMode.DOWN)
.doubleValue();
}
But, due to the loss of precision, it returns somewhat unexpected results:
truncate(0.2, 1) #=> 0.2
truncate(0.3, 1) #=> 0.2
truncate(0.4, 1) #=> 0.4
truncate(0.2, 3) #=> 0.2
truncate(0.3, 3) #=> 0.299
truncate(0.4, 3) #=> 0.4
This begs for two questions:
Is it how it's supposed to work for
0.3
? Why would there be a loss of precision in this case? Doesn't it defeat the whole purpose of havingBigDecimal
?How do I correctly truncate my values?
Thanks.