Why would you call doubleValue()
? Just avoid doing that. There are two problems with it:
- A
double
has no notion of trailing zeroes, unlikeBigDecimal
- Converting between
double
andBigDecimal
(in either direction) is almost always a bad idea. They're generally used for different kinds of values - e.g. physical dimensions like height and weight are best fordouble
; artificial values such as currency are best forBigDecimal
Without the call to doubleValue()
you're fine:
import java.math.*;
public class Test {
public static void main(String[] args) {
String input = "0.4595";
int places = 3;
BigDecimal dec = new BigDecimal(input)
.setScale(places, BigDecimal.ROUND_HALF_EVEN);
System.out.println(dec); // Prints 0.460
}
}