简体   繁体   中英

python saving the excess of a float to int conversion

x=10.5
    if x==10.5:
        x=int(x)+1
        y= .5

ok i have x=10.5 i want to round up to 11 but say the .5 to use later is there any way to do this when i dont know what x will be all the time?

i have to real place to start or even if its possible i do know how to change it to an int but i want to store what ever it took off and store to y right now id have to write 100 of if statments to figure what do say and that just doent strike me as the best way to do it

One fell swoop:

>>> divmod(10.5,1)
(10.0, 0.5)

The docs for divmod can be found here .

x = 10.5
x,chopped = int(x), x - int(x)

take the number modulus 1

>>> 10.5%1
0.5

This question is rather poorly worded. Is this what you are trying to do?

x = 10.5

y = math.fmod(x, 1.0) # y = 0.5
x = math.ceil(x) # x = 11.0

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM