1. 程式人生 > 其它 >保留小數位的五種方式------Python

保留小數位的五種方式------Python

技術標籤:Python字串python

1. format
print("{0:.2}".format("2.235648"))  # 字串保留兩位小數
print("{0:.2f}".format(6.423789))  # float保留兩位小數
print("{0:b}".format(4))  # 二進位制輸出,物件是整數
print("{0:c}".format(4))  # Unicode輸出,物件是整數
print("{0:d}".format(4))  # decimal型別輸出,物件是整數
print("{0:o}".format(4)) # 八進位制輸出,物件是整數 print("{0:x}".format(4234)) # 十六進位制輸出,物件是整數,字母小寫 print("{0:4X}".format(4234)) # 十六進位制輸出,物件是整數,字母大寫 print("{0:e}".format(6.423789)) # 科學計數法小寫e print("{0:E}".format(6.423789)) # 科學計數發大寫E print("{0:%}"
.format(6.423789)) # 百分之幾輸出

輸出結果
在這裡插入圖片描述

2. %f
print("%.4f" % 7.1264989)
print("%.f" % Decimal("7.1264989"))

輸出結果

7.1265
7
3. round(不推薦)

只能是float或Decimal型別

from decimal import Decimal
print(round(8.356987, 3))
print(round(Decimal(8.356987), 2))

輸出結果

8.357
8.36
4. Decimal

這個型別一般會在讀取excel表格中遇到

from decimal import Decimal
print(Decimal('5.592134').quantize(Decimal('0.000')))
print(Decimal('5.592134').quantize(Decimal('237746.450')))

輸出結果

5.592
5.592

注意:
Decimal這種方式,當保留位數大於等於5時,前一位是奇數則進一,前一位若是偶數則不進位直接捨去
如:

print(Decimal('789.125').quantize(Decimal('0.00')))
print(Decimal('789.135').quantize(Decimal('0.00')))

輸出結果

789.12
789.14
5. 捨去(不入)

不管後面是數字幾或者多少位,全部捨去不要了

print(int(48.54861 * 100) / 100)
print("65.5479789"[:7])
s = "78.78994648".split(".")
print("初s:", s)
s[1] = s[1][:3]
print("次s", s)
print(".".join(s))

輸出結果:

48.54
65.5479
初s: ['78', '78994648']
次s ['78', '789']
78.789