2011-04-28 30 views
0

我想在python中取整一些不同的規則。例如;在Python中的舍入規則

10.666 = 10.6 
10.667 = 10.7 

即倒在6,和高達第7

有沒有一種方法,我可以使用Python做到這一點?

+3

「一些隨機規則」?請詳細說明。 – delnan 2011-04-28 23:16:37

+0

換句話說。規則是不同的:) – SpaghettiMonster 2011-04-28 23:23:31

+0

爲什麼你需要這樣做?只是好奇。 – 2011-04-28 23:33:45

回答

1

我不確定你想到的是什麼樣的舍入規則。你能詳細說明你的舍入規則嗎?

所以我不能說這是正是正確的,但我懷疑,你可以用它作爲您的實現模式。

def cround(v): 
    """ 
    Round number down at 1st decimal place when the digit in the 
    3rd decimal place is <= 6, up when >= 7 
    """ 
    v *= 10 
    q = str(round(v, 2)) 
    if int(q[-1]) <= 6: 
     return int(v)/10.0 
    return round(v)/10.0 

NUMS = [ 
    10.666, 10.667, 0.1, 1.0, 10.11, 10.22, 10.06, 10.006, 11.6, 11.7, 
    10.666123, 10.667123, 10.888, 10.999 ] 

for num in NUMS: 
    print str(num).ljust(11), cround(num) 

輸出:

10.666  10.6 
10.667  10.7 
0.1   0.1 
1.0   1.0 
10.11  10.1 
10.22  10.2 
10.06  10.0 
10.006  10.0 
11.6  11.6 
11.7  11.7 
10.666123 10.6 
10.667123 10.7 
10.888  10.9 
10.999  11.0 
0

是的,你可以。由於您沒有對規則進行描述,但我認爲您知道您想要什麼,您可以將數字轉換爲字符串,將其逐個字符地迭代,並且一旦到達小數點後兩位的字符。你可以根據你的規則行事。

還有一個功能,它可以將數字四捨五入到給定的精度。

0

下面是做到這一點(使用simplebias的測試數據)

>>> def cround(v): 
...  return round(v-2.0/9, 1)+.2 
... 
>>> 
>>> NUMS = [ 
...  10.666, 10.667, 0.1, 1.0, 10.11, 10.22, 10.06, 10.006, 11.6, 11.7, 
...  10.666123, 10.667123, 10.888, 10.999 ] 
>>> 
>>> for num in NUMS: 
...  print str(num).ljust(11), cround(num) 
... 
10.666  10.6 
10.667  10.6 
0.1   0.1 
1.0   1.0 
10.11  10.1 
10.22  10.2 
10.06  10.0 
10.006  10.0 
11.6  11.6 
11.7  11.7 
10.666123 10.6 
10.667123 10.6 
10.888  10.9 
10.999  11.0 
1

如果你想要的是圍捕如果部分待四捨五入大於某種方式等於其最大值的⅔,否則回合下來,那麼我相信你可以先減去⅙*想精確使用純round()功能:

def my_round(n): 
    return round(n - .1/6, 1) 

>>> print(my_round(10.666)) 
10.6 
>>> print(my_round(10.667)) 
10.7 
-2

我想科ep儘可能簡單。

您有三個功能可用ceil,floor,round。舍入規則如下:

  • ceil()輪時,這意味着:

    ceil(10.1) = 11ceil(10.9) = 11

  • floor()回合下來,這意味着:

    floor(10.1) = 10floor(10.9) = 10

  • round()取決於你的值(這裏,向上(> = 10.5)或向下(< 10。5)),這意味着:

    round(10.1) = 10round(10.9) = 11

如果使用ceilfloor首先必須導入數學模塊,例如from math import ceil

欲瞭解更多信息,我建議你看看這裏:Floating Point Arithmetic: Issues and Limitations

+0

Python中的round(10.5,0)'不會繞過10.5到11.它返回10!爲什麼? – Dmitry 2017-10-20 00:10:19