0

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);
  • 1
    Then you need not round but to truncate digits. Because 8.775 would be rou ded ru 8.78 according to usual rounding rules – Ivan Jun 03 '20 at 22:39
  • Building on what @Ivan said I would just find the index of the decimal and then take the substring from 0, index + 2. Be careful and make sure that the string is also that long. – Major Ben Jun 03 '20 at 22:43
  • You want to do [this](https://stackoverflow.com/questions/7747469/how-can-i-truncate-a-double-to-only-two-decimal-places-in-java) – Maxqueue Jun 03 '20 at 22:45

3 Answers3

3

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
elec
  • 117
  • 1
  • 9
3

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
RaffleBuffle
  • 3,915
  • 1
  • 6
  • 13
0
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
Minar Mahmud
  • 2,289
  • 6
  • 18
  • 29