How can I truncate a double to only two decimal places in Java?
For example I have the variable 3.545555555, which I would want to truncate to just 3.54.
If you want that for display purposes, use java.text.DecimalFormat
:
new DecimalFormat("#.##").format(dblVar);
If you need it for calculations, use java.lang.Math
:
Math.floor(value * 100) / 100;
DecimalFormat df = new DecimalFormat(fmt);
df.setRoundingMode(RoundingMode.DOWN);
s = df.format(d);
Check available RoundingMode
and DecimalFormat
.
None of the other answers worked for both positive and negative values ( I mean for the calculation and just to do "truncate" without Rounding). and without converting to string.
From the How to round a number to n decimal places in Java link
private static BigDecimal truncateDecimal(double x,int numberofDecimals)
{
if ( x > 0) {
return new BigDecimal(String.valueOf(x)).setScale(numberofDecimals, BigDecimal.ROUND_FLOOR);
} else {
return new BigDecimal(String.valueOf(x)).setScale(numberofDecimals, BigDecimal.ROUND_CEILING);
}
}
This method worked fine for me .
System.out.println(truncateDecimal(0, 2));
System.out.println(truncateDecimal(9.62, 2));
System.out.println(truncateDecimal(9.621, 2));
System.out.println(truncateDecimal(9.629, 2));
System.out.println(truncateDecimal(9.625, 2));
System.out.println(truncateDecimal(9.999, 2));
System.out.println(truncateDecimal(-9.999, 2));
System.out.println(truncateDecimal(-9.0, 2));
Results :
0.00
9.62
9.62
9.62
9.62
9.99
-9.99
-9.00
Note first that a double
is a binary fraction and does not really have decimal places.
If you need decimal places, use a BigDecimal
, which has a setScale()
method for truncation, or use DecimalFormat
to get a String
.