0

I need to do a custom rounding that works that way:

  • If number is closer to 0, it is rounded down (1 or 2)
  • If number is closer to 0.5, it is rounded to 0.5 (3, 4, 6 or 7)
  • If number is closer to 1, it is rounded up (8 or 9)

What would be the best approach to this problem?

Edit: this question was already answered in "Java round to nearest .5". Thanks for the answers.

EAG
  • 1
  • 1
  • 1
    Sounds like you simply want to round to the nearest multiple of 0.5. Is that correct? – Mark Dickinson May 26 '22 at 12:53
  • 3
    I don't understand what the "1 or 2", "3, 4, 6 or 7" or "8 or 9" mean. Likewise "If number is closer to 0" - closer to 0 than what? Some examples would be really helpful here, along with a rewording to make it as clear as possible. – Jon Skeet May 26 '22 at 12:53

1 Answers1

1

I assume that you are looking at numbers in the range 0.0 to 1.0. You could work with the range boundaries you give. If num < 0.3 return 0.0, or if num < 0.8 return 0.5, otherwise return 1.0

rossum
  • 15,344
  • 1
  • 24
  • 38