-4

I want to calculate the bill where need to do some rounding

What i expect is:

it should be nearest 10 cents. e.g:

10.17 -> 10.20 (round up)

10.11 -> 10.10 (round down)

I have tried to use:

grandTotal = Double.valueOf(String.format(Locale.ENGLISH, "%.2f", grandTotal));

but it will occur error when the total look like 12.15, 14.65, 19.85.

By right, it should round up, but my result shows it round down.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Peter Guo
  • 182
  • 1
  • 11

2 Answers2

1

To represent monetary values with cents, you should only use integers (as cents), String or BigDecimal, not floats or doubles because floating-point values can't exactly represent all decimal values.

To round up to the first digit after comma, you can do:

BigDecimal value = new BigDecimal("10.17");
BigDecimal rounded = value.setScale(1, BigDecimal.ROUND_HALF_UP);
BladeCoder
  • 12,779
  • 3
  • 59
  • 51
1

My two cents for a possible solution:

Double value = 14.65;
Double grandTotal = Math.round(value * 10)/10;