簡體   English   中英

最后一位數為5的數字的舍入

[英]Roundoff of a number having 5 as last digit

我想要舍棄一個最后有5個的數字。 如果十進制值> = 5,則Python round函數將十進制數round入為ceil整數。

我想要round(30.195,2)輸出30.19但是python給出30.2

你可以用這個:

int(30.195*100)/100

30.195回合到30.2因為0.005被舍入,導致30.19 + 0.01 = 30.20 ,這對於舍入是合適的。

請注意,上面的方法會刪除最后一位數字,不會進行舍入 - 這是獲得所需結果所需的內容。 所以下面給出了30.19的相同答案:

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

以下是函數形式的解決方案:

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

print(chop_off(30.195,2))

在你想要向下舍入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

你可以從你擁有的所有數字中減去0.001,並保存在一個單獨的列表中。 這樣,圓函數將按您的意願工作。 30.195將變為30.194並且四舍五入至30.19 30.196將變為30.195並且四舍五入至30.20

如果沒有,你可以運行一個for循環並檢查第三個小數位是否為5,然后手動將其向下舍入,否則使用內置的round函數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM