一、保留兩位小數 且 做四舍五入處理
四舍六入五成雙, 四舍六入五湊偶的意思, 根據百度詞條的解釋如下:
(1)當精確位后面一位的數字是1-4的時候,舍去
(2)當精確位后面一位的數字是6-9的時候,進1位
(3)當精確位后面一位的數字是5的,此時需要看這個5后面是否還有值。如果5后面有值(0忽略),則直接進位;
(4)如果5后面沒值或值為0,則需要判斷5前面的值是偶數還是奇數。
(5)如果5前面是偶數,不進位;如果是奇數,進位。
1、使用字符串格式化
1
2
3
4
|
>>> x = 3.1415926 >>> print ( "%.2f" % x) 3.14 >>> |
2、使用python內置的round() 函數
1
2
3
4
|
>>> x = 3.1415926 >>> round (x, 2 ) 3.14 >>> |
round()函數的官方定義:
1
2
3
4
5
6
7
8
9
|
def round (number, ndigits = None ): # real signature unknown; restored from __doc__ """ round(number[, ndigits]) -> number Round a number to a given precision in decimal digits (default 0 digits). This returns an int when called with one argument, otherwise the same type as the number. ndigits may be negative. """ return 0 |
3、使用python內置的decimal模塊
decimal 英 /'des?m(?)l/ 小數的
quantize 英 /'kw?nta?z/ 量化
1
2
3
4
5
6
7
8
9
10
11
12
|
>>> from decimal import Decimal >>> x = 3.1415926 >>> Decimal(x).quantize(Decimal( "0.00" )) Decimal( '3.14' ) >>> a = Decimal(x).quantize(Decimal( "0.00" )) >>> print (a) 3.14 >>> type (a) < class 'decimal.Decimal' > >>> b = str (a) >>> b '3.14' |
二、保留兩位小數 且 不做四舍五入處理
1、使用序列中的切片
1
2
3
|
>>> x = 3.1415926 >>> str (x).split( "." )[ 0 ] + "." + str (x).split( "." )[ 1 ][: 2 ] '3.14' |
2、使用re正則匹配模塊
1
2
3
4
|
>>> import re >>> x = 3.1415926 >>> re.findall(r "\d{1,}?\.\d{2}" , str (a)) [ '3.14' ] |
通過計算的途徑,很難將最終結果截取2位,我們直接想到的就是如果是字符串,直接截取就可以了。
例如
1
2
3
|
num = '1234567' #字符串num print (num[: 3 ]) |
結果:
123
如果是123.456取2位小數(截取2位小數),值需要把小數點右邊的當做字符串截取即可
總結
到此這篇關于python保存兩位小數的文章就介紹到這了,更多相關python保存兩位小數內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://shliang.blog.csdn.net/article/details/89156676