1. 程式人生 > >python中小數點後取2位(四捨五入)以及取2位(四舍五不入)

python中小數點後取2位(四捨五入)以及取2位(四舍五不入)

一.小數點後取2位(四捨五入)的方法
方法一:round()函式
其實這個方法不推薦大家使用,查詢資料發現裡面的坑其實很多,python2和python3裡面的坑還不太一樣,在此簡單描述一下python3對應的坑的情況。

a = 1.23456
b = 2.355
c = 3.5
d = 2.5
print(round(a, 3))
print(round(b, 2))
print(round(c))
print(round(d))

結果:

1.235 # 1.23456最終向前進位了
2.35 # 2.355居然沒進位
4 # 最終3.5居然變為4了
2 # 最終2.5取值變為2

(1)通過上面的函式,看著是不是很暈,感覺round(x,n)函式是否進位也沒看出是啥規律
(2)round(x,n)函式中,是否進位或四捨五入,取決於n位以及n+1位小數的值
(3)只有當n+1位數字是5的時候,容易混淆,如果n為偶數,則n+1位數是5,則進位,例如round(1.23456,3)最終變為1.235
(4)如果n為奇數,則n+1位是數5,那不進位,例如round(2.355,2),最終為2.35
(5)如果n為0,即沒有填寫n的時候,最終結果與上面相反,即整數部分為偶數的時候,小數位5不進位,例如(round(2.5)變為2)。
(6)整數部分為奇數的時候,小數位5進位。(round(3.5)變為4)
看完如上的部分,感覺是不是更暈了,所以round()不推薦使用,目前也不知道設計這個函式的目的在哪裡?有誰知道麻煩告知一下?

方法二:’%.2f’ %f 方法
f = 1.23456

print('%.4f' % f)
print('%.3f' % f)
print('%.2f' % f)

結果:

1.2346
1.235
1.23

(1)這個方法是最常規的方法,方便實用,居家旅行必備!
方法三:Decimal()函式
from decimal import Decimal

aa = Decimal('5.026').quantize(Decimal('0.00'))
bb = Decimal('3.555').quantize(Decimal('0.00'))
cc = Decimal('3.545').quantize(Decimal('0.00'))print(aa)

print(bb)
print(cc)
9
結果:

5.03
3.56
3.54
decimal這個模組在很少用,如上圖中,3.555結果為3.56,而3.545結果變為3.54,一個5進位了,一個是5沒進位,具體原因不詳。
所以不推薦使用這個方法!!!

二.小數點後取2位(四舍五不入)的方法
通過計算的途徑,很難將最終結果擷取2位,我們直接想到的就是如果是字串,直接擷取就可以了。
例如

num = '1234567' #字串num
print(num[:3])

結果:
123

如果是123.456取2位小數(擷取2位小數),值需要把小數點右邊的當做字串擷取即可
partition()函式(將字串根據字串切割):
http://www.runoob.com/python/att-string-partition.html

num = '123.4567'
num_str = num.partition(".")
print(num_str)

結果:
('123', '.', '4567') # 三個元素的元祖

拼接字串:format()函式的使用
https://blog.csdn.net/i_chaoren/article/details/77922939

方法一:
def get_two_float(f_str, n):
a, b, c = f_str.partition('.')
c = c[:n]
return ".".join([a, c])


num = "123.4567" #(1)隱患一,傳入函式的是字串
print(get_two_float(num, 2))

num2 = '123.4' # (2)隱患二,如果傳入的字串小數位小於最終取的位數
print(get_two_float(num2, 2))
結果:

123.45
123.4
最終版本:

def get_two_float(f_str, n):
f_str = str(f_str) # f_str = '{}'.format(f_str) 也可以轉換為字串
a, b, c = f_str.partition('.')
c = (c+"0"*n)[:n] # 如論傳入的函式有幾位小數,在字串後面都新增n為小數0
return ".".join([a, c])


num = 123.4567
print(get_two_float(num, 2))

num2 = 123.4
print(get_two_float(num2, 2))