I have a double number which is 8.775. I want to make it to where it'll print 8.77. I tried this line of code but Java keeps rounding it to 8.78. Is there any way around this?
System.out.printf("%.2f", 8.775);
I have a double number which is 8.775. I want to make it to where it'll print 8.77. I tried this line of code but Java keeps rounding it to 8.78. Is there any way around this?
System.out.printf("%.2f", 8.775);
For rounding double to the floor you would have to write your own function(or use DecimalFormat) or you can for example use Bigdecimal which already has this built-in.
System.out.println(BigDecimal.valueOf(8.775).setScale(2, BigDecimal.ROUND_FLOOR));
Output:
8,77
If you want control over the rounding used in converting a double
to a String
you need to use DecimalFormat
.
You either want FLOOR
,which rounds towards negative infinity, or DOWN
, which rounds towards zero, depending on the desired behavior with negative numbers (for positive numbers they produce the same results):
DecimalFormat df = new DecimalFormat(".##");
df.setRoundingMode(RoundingMode.FLOOR);
System.out.println("FLOOR");
System.out.println(df.format(8.775));
System.out.println(df.format(-8.775));
System.out.println("DOWN");
df.setRoundingMode(RoundingMode.DOWN);
System.out.println(df.format(8.775));
System.out.println(df.format(-8.775));
Output:
FLOOR
8.77
-8.78
DOWN
8.77
-8.77
double val = 8.775;
double output = new BigDecimal(val)
.setScale(2, RoundingMode.FLOOR)
.doubleValue();
System.out.println(output); // 8.77
System.out.printf("%.2f\n", output); // 8.77