1

I have the following code:

LocalTime time = LocalTime.now();
BigDecimal res = new BigDecimal(time.getMinute()).divide(new BigDecimal(60), 4, RoundingMode.HALF_UP);

and I want the following results to occur:

55/60 = 0.9167
17/60 = 0.2833

I am wondering what type of rounding I should use for these results. At the moment I am using RoundingMode.HALF_UP but I'm unsure whether this is the right mode to be using in order to get these results.

buræquete
  • 12,943
  • 4
  • 34
  • 69
jcm
  • 4,879
  • 9
  • 39
  • 64
  • You should phrase your expected rounding behaviour in words and then see if it matches HALF_UP. FWIW, it should produce the two cases you mentioned (but you can test that). Unless you need to handle negative numbers, this should be pretty straightforward. – Thilo Feb 25 '16 at 03:34
  • 2
    Did you try with different rounding modes and enough use cases to determine which one you want? That would be a lot quicker than waiting for an answer here, since we don't know what you want mathematically given just two examples. – Jim Garrison Feb 25 '16 at 03:35
  • Why do you need BigDecimal here anyway? You can round `double` as well. – Thilo Feb 25 '16 at 03:36
  • Yes that is the right mode. or perhaps you want to give more sample input and expected output. – Baby Feb 25 '16 at 03:36
  • Though a bit unnecessary to use `BigDecimal` here, you are using the correct `RoundingMode` for your expectations; for more information please check; https://docs.oracle.com/javase/7/docs/api/java/math/RoundingMode.html – buræquete Feb 25 '16 at 03:37
  • @Thilo do you mean `Double`? How would I round a primitive `double`? – jcm Feb 25 '16 at 03:51
  • http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java – Thilo Feb 25 '16 at 03:53
  • You shouldn't even be rounding your number at all. There is no reason throw away precision. Just `time.getMinute() / 60.0` is perfectly adequate. If you want to *display* a number with only four digits of decimal precision, you should use a NumberFormat or Formatter. – VGR Feb 25 '16 at 13:40

0 Answers0