简体   繁体   中英

Roundoff of a number having 5 as last digit

I want to roundoff a number which has 5 in last. Python round function rounds the decimal number to ceil integer if decimal value >=5.

I want round(30.195,2) to output 30.19 but python gives 30.2

You can use this:

int(30.195*100)/100

30.195 rounds to 30.2 because 0.005 is rounded up, resulting in 30.19 + 0.01 = 30.20 which is fine for rounding.

Note that my method above chops off the last digit, no rounding - which is what you would need to get the result you want. So both the below gives the same answer of 30.19 :

int(30.199*100)/100
int(30.191*100)/100

Here is the solution in function form:

def chop_off(val, places):
    return int(val*10**places)/10**places

print(chop_off(30.195,2))

In your case where you want to round down on 0.005 you can use this:

import math

def round_off(val, places):
    last_digit = val*10**(places+1)%10
    if last_digit > 5:
        return math.ceil(val*10**places)/10**places
    else:
        return math.floor(val*10**places)/10**places
    return int(val*10**places)/10**places

print(chop_off(30.194,2))  # 30.19
print(chop_off(30.195,2))  # 30.19
print(chop_off(30.196,2))  # 30.20

you can subtract 0.001 from all the numbers you have and save in a separate list. that way, the round function will work as you wish. 30.195 will become 30.194 and rounded off to 30.19 30.196 will become 30.195 and rounded off to 30.20

if not, you can run a for loop and check if the 3rd decimal place is 5, then round it down manually, else use the builtin round function

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