Python浮點數控制小數精度

將精度高的浮點數轉換成精度低的浮點數。git

1.round()內置方法

這個是使用最多的,剛看了round()的使用解釋,也不是很容易懂。round()不是簡單的四捨五入的處理方式。函數

For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2).ui

 

 round()若是隻有一個數做爲參數,不指定位數的時候,返回的是一個整數,並且是最靠近的整數(這點上相似四捨五入)。可是當出現.5的時候,兩邊 的距離都同樣,round()取靠近的偶數,這就是爲何round(2.5) = 2。當指定取捨的小數點位數的時候,通常狀況也是使用四捨五入的規則,可是碰到.5的這樣狀況,若是要取捨的位數前的小樹是奇數,則直接捨棄,若是偶數這 向上取捨。看下面的示例:ip

2. 使用格式化

效果和round()是同樣的。it

 

 

既然說到小數,就必然要說到整數。通常取整會用到這些函數:方法

1. round()

這個不說了,前面已經講過了。必定要注意它不是簡單的四捨五入,而是ROUND_HALF_EVEN的策略。im

2. math模塊的ceil(x)

取大於或者等於x的最小整數。img

3. math模塊的floor(x)

去小於或者等於x的最大整數。di

 

相關文章
相關標籤/搜索