You can’t set the precision of a double (or Double) to a specified number of decimal digits, because floating-point values don’t have decimal digits. They have binary digits.
You will have to convert into a decimal radix, either via BigDecimal or DecimalFormat, depending on what you want to do with the value later.
DecimalFormat df = new DecimalFormat("#.####");
df.setRoundingMode(RoundingMode.CEILING);
for (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324)) {
Double d = n.doubleValue();
System.out.println(df.format(d));
}
You can try BIGDECIMAL for this purpose Double toBeTruncated = new Double("3.5789055"); Double truncatedDouble = new BigDecimal(toBeTruncated) .setScale(3, BigDecimal.ROUND_HALF_UP) .doubleValue();