0

How do I round a fraction to the nearest 0.5 between 0.0 and 5.0?

Let's say I've got 11/150, it should convert to 0.0. In addition, 75/150 should convert to 2.5

As for the code I've got this but I'm lost as to where to go from here

# number is 11, and max is 150

number = float(percent / max)
number = round(p/0.5)*0.5

However, it needs to round between 0.0 and 5.0 rather than 0 and 1.

EDIT 1:

It's best to treat it as a percentage. For example, let's say the percent given is 5o% (50/100, for ease). This means the result should be 2.5

In the same respect, 51% would still be 2.5.

However, 60% (60/100) would be 3.0

Trent112232
  • 169
  • 8
  • @B__ Clarified in extra line, it basically needs to treat it like a percentage, with the cap being 5.0 and the minimum being 0.0 – Trent112232 Feb 07 '22 at 13:57
  • Per the existing "already has answers" link, for non int values see this answer: https://stackoverflow.com/a/18666678/361842 – JohnLBevan Feb 07 '22 at 13:59
  • @JohnLBevan That doesn't do it between two values. – Trent112232 Feb 07 '22 at 15:12
  • Alternative solution since you seem interested in fractions: `from fractions import Fraction; def round_to_half(numerator, denominator): return Fraction(numerator, denominator).limit_denominator(2)` – Stef Feb 07 '22 at 16:57

1 Answers1

2

Multiply by 2, round, then divide by 2

if you want nearest quarter, multiply by 4, divide by 4, etc

Naswih
  • 21
  • 3