1

I want to round up a double value in java. Always to round up the value in ispite that matematecally correct way, sometimes, is round down the value. For example:

value = 6.5817

I want to round up, keeping two decimals. So I need the value will be like this:

value = 6.59

The important thing here is always keep two decimals and always round up the second decimal if the value have more two decimals.

Have someone idea how I can to do this in java?

2 Answers2

9

Since double values are inexact, e.g. it cannot store a number like 0.07 exactly, you need to use BigDecimal to help round up a double value, with the least probability of getting the wrong value.

To round to 2 decimals, use:

double value = 6.5817;
double roundedUp = BigDecimal.valueOf(value).setScale(2, RoundingMode.UP).doubleValue();
System.out.println(roundedUp); // prints 6.59

Note that this code prints 0.07 when value = 0.07, unlike e.g. Math.ceil(value * 100.0) / 100.0, which incorrectly prints 0.08.

Andreas
  • 138,167
  • 8
  • 112
  • 195
0

Try the following:

double a = 6.5817;
Math.ceil(a * 100.0) / 100.0;
Athanasios Kataras
  • 20,791
  • 3
  • 24
  • 45
  • Since doubles are inexact, you get incorrect results like `a = 0.07` -> `0.08`, i.e. it rounded up a number that didn't need rounding. – Andreas Aug 27 '20 at 21:03