[英]Roundoff of a number having 5 as last digit
I want to roundoff a number which has 5 in last. 我想要舍弃一个最后有5个的数字。 Python
round
function rounds the decimal number to ceil integer if decimal value >=5. 如果十进制值> = 5,则Python
round
函数将十进制数round
入为ceil整数。
I want round(30.195,2)
to output 30.19
but python gives 30.2
我想要
round(30.195,2)
输出30.19
但是python给出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. 30.195
回合到30.2
因为0.005
被舍入,导致30.19 + 0.01 = 30.20
,这对于舍入是合适的。
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
: 所以下面给出了
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: 在你想要向下舍入0.005的情况下,你可以使用:
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. 你可以从你拥有的所有数字中减去0.001,并保存在一个单独的列表中。 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
30.195将变为30.194并且四舍五入至30.19 30.196将变为30.195并且四舍五入至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 如果没有,你可以运行一个for循环并检查第三个小数位是否为5,然后手动将其向下舍入,否则使用内置的round函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.