Is there a way in Python to round the number up only if the fractional part is larger than a half? round
and math.ceil
will do this:
round(X.5) => X+1
math.ceil(X.5) => X+1
however, I want this:
x.500...000001 => x+1
x.500...000000 => x
How to do that?
I have 2.7.13 python x64
math.ceil(x-0.5)
maps:
12.50 -> ceil(12.00) -> 12
12.49 -> ceil(11.99) -> 12
12.51 -> ceil(12.01) -> 13
You can do something like this:
round(X - 0.00000000001)
You will need to decide how many decimal places are appropriate, bearing in mind that floats are not exact, so for example 10000000000000000000.5 can't be represented.
I found the answer as suggested by jonrsharpe to use context This is they way I used it:
from decimal import *
x =5.500000000000001 # it is the number wanted to round, however only takes 15 number after decimal for me
ctx= Context(prec=1, rounding=ROUND_HALF_DOWN)
y = ctx.create_decimal(x)
However, I do not know if it is going to work with everybody. probably there is a better way to put it.
import math
while True:
num=input("num: ")
num=float(num)
new_n=round(num,0)
if (float(new_n)-0.5)==num:
print(num-0.5)
else:
print(new_n)
output:
num: 4.5
4.0
num: 5.5
5.0
num: 6.6
7.0
num: 5.5001
6.0
well I had to do some thinking but this should do what you want
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.