0

I've been using Math.round and everything seemed fine until I noticed that any number that ended in "5" wasn't rounded.

double roundtotal = Math.round(total * 100.0) / 100.0;

Which rounds to 2 decimal places, but doesn't round 46.565 to 46.57 for example

Can anyone help?

JimmyB
  • 1
  • 3
  • Works for me: http://pastie.org/8232041 – T.J. Crowder Aug 13 '13 at 08:21
  • 1
    It does here http://ideone.com/20A6rb prints `46.565 rounded to 2 places is 46.57` – Peter Lawrey Aug 13 '13 at 08:21
  • `System.out.println(Math.round(46.565 * 100.0) / 100.0);` Output: `46.57`. – Marko Topolnik Aug 13 '13 at 08:23
  • ah solved it, accidentally made total a float, thanks for pointing it out – JimmyB Aug 13 '13 at 08:26
  • 1
    This is *dangerous*! Remember that your machine uses binary floats, so `46.565` *is not* exactly 46 and 565 thousandths. It's an approximation which is either a tiny amount larger than the exact decimal value, or a tiny amount smaller. And if it's a tiny amount larger, it should round up, while if it's a tiny amount smaller, it should round down. You shouldn't have any expectations about which direction a binary approximation to a decimal halfway case will round. – Mark Dickinson Aug 13 '13 at 08:50
  • 1
    See [this answer](http://stackoverflow.com/a/12684082/207421) for why that doesn't and cannot work. – user207421 Aug 13 '13 at 09:54

1 Answers1

0

You could do this:

double roundtotal = ((int)((total*100.0)+0.5)) / 100.0;
MrSmith42
  • 9,961
  • 6
  • 38
  • 49