python中怎么精确20位_Python中的精确处理
Python可以使用不同的函數(shù)來處理浮點數(shù)的精度。數(shù)學模塊中定義了大多數(shù)用于精確處理的函數(shù)。因此,要使用它們,首先我們必須將math模塊導入到當前命名空間中。import?math
現(xiàn)在,我們將看到一些用于精確處理的功能。
該trunc()方法
該trunc()方法用于從浮點數(shù)中刪除所有小數(shù)部分。因此,它僅返回數(shù)字中的整數(shù)部分。
該ceil()方法
該ceil()方法用于返回數(shù)字的Ceiling值。天花板值是最小的整數(shù),大于整數(shù)。
該floor()方法
該floor()方法用于返回數(shù)字的下限值。Floor值是最大的整數(shù),小于整數(shù)。
范例程式碼
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
如我們所見,使用上述函數(shù),我們可以刪除小數(shù)部分并獲得確切的整數(shù)。現(xiàn)在,我們將看到如何使用更有效的方法來管理小數(shù)部分。
運算符
%運算符用于在Python中格式化和設置精度。
該format()方法
該format()方法還用于格式化字符串以設置正確的精度
round(a,n)函數(shù)
該round()方法用于四舍五入數(shù)字a,最多n個小數(shù)位
范例程式碼
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
總結
以上是生活随笔為你收集整理的python中怎么精确20位_Python中的精确处理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: libiconv移植
- 下一篇: php libiconv close_P