0

I want to make a program that will round up a float number like: 18.33333 to 18.5.

I tried math.ceil but It wont work like I expected.

import math

number1 = 18.3333

print(math.ceil(float(number1)))

I want it to be 18.5. But it turns out as 19.

2 Answers2

0

You could just double, round then cut in half. Sort of a work around, but does the job:

import math

number1 = 18.3333


round(number1*2)/2

Or use a function:

def mod_round(x, base=.5):
    return (base * round(float(x)/base))

mod_round(number1. base=.5)
chitown88
  • 27,527
  • 4
  • 30
  • 59
0

You can round x/2, then multiply by 2:

def round_to_half(x):
    return round(x*2)/2

for test in [0.12, 0.26, 13.78, 14.27]:
    print(test, round_to_half(test))

Output:

0.12 0.0
0.26 0.5
13.78 14.0
14.27 14.5    
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50