前言

​ 使用 int() 函式做數值轉換, 會遇到小數點以下有值時, 會被無條件捨去的困擾,

從 stackoverflow 看到有兩種解法

>>> num1 = 1.0
>>> int(num1)
1
>>> num2 = 1.5
>>> int(num2)
1

解法一

​ 使用 is_integer() 函式配合 if 判斷是否為整數, 是才做 int() 轉換

>>> (1.0).is_integer()
True
>>> (1).is_integer()       ### 缺點是已經是整數的變數, 會跳錯
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'is_integer'
>>> (1.5).is_integer()
False
>>> (0.9999999999 ).is_integer()
False
>>> data = [1.0, 1, 1.5, 0.9999999999]
>>> print(list(map(lambda x: int(x) if int(x) == x else x, data)))   ### 運用 lambda 的特性可以避免例外
[1, 1, 1.5, 0.9999999999]

解法二

​ 使用 ‘%g’` (“General Format) 處理

>>> >>> '%g' % 1.0
'1'
>>> '%g' % 1
'1'
>>> '%g' % 1.5
'1.5'
>>> '%g' % 0.9999999999      ### 缺點是趨近於 1 的數值仍然會被捨去
'1'
>>> '%.10g' % 0.9999999999   ### 調高格式化的長度
'0.9999999999'

Reference

Python: return float 1.0 as int 1 but float 1.5 as float 1.5]