Python中的精度處理


Python可以使用不同的函式來處理浮點數的精度。大多數精度處理函式都在math模組中定義。因此,要使用它們,首先必須將math模組匯入到當前名稱空間。

import math

現在我們將看到一些用於精度處理的函式。

trunc()函式

trunc()方法用於去除浮點數的所有小數部分。因此,它只返回數字的整數部分。

ceil()函式

ceil()方法用於返回數字的向上取整值。向上取整值是大於該數字的最小整數。

floor()函式

floor()方法用於返回數字的向下取整值。向下取整值是小於該數字的最大整數。

示例程式碼

線上演示

import math
number = 45.256
print('Remove all decimal part: ' + str(math.trunc(number)))
print('Ceiling Value: ' + str(math.ceil(number)))
print('Floor Value: ' + str(math.floor(number)))

輸出

Remove all decimal part: 45
Ceiling Value: 46
Floor Value: 45

正如我們所看到的,使用上述函式,我們可以去除小數部分並獲得精確的整數。現在我們將看到如何使用更有效的方法來管理小數部分。

%運算子

%運算子用於在Python中格式化和設定精度。

format()函式

format()方法也用於格式化字串以設定正確的精度。

round(a, n)函式

round()方法用於將數字a四捨五入到n位小數。

示例程式碼

線上演示

import math
number = 45.25656324
print('Value upto 3 decimal places is %.3f' %number)
print('Value upto 4 decimal places is {0:.4f}'.format(number))
print('Round Value upto 3 decimal places is ' + str(round(number, 3)))

輸出

Value upto 3 decimal places is 45.257
Value upto 4 decimal places is 45.2566
Round Value upto 3 decimal places is 45.257

更新於:2019年7月30日

3K+ 瀏覽量

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.