Python教程-如何在Python中去掉小数部分

我们在Python中使用不同类型的数字,并根据需要修改它们的类型。
在本教程中,我们将讨论如何在Python中去掉小数部分。
让我们从一个简单的程序开始,
a = 24
print(type(a))
b = 19.4
print(type(b))
c = 3+4j
print(type(c))
输出:
<class 'int'>
<class 'float'>
<class 'complex'>
解释:
在上面的程序中,我们分别将a、b和c声明为24、19.4和3+4j。
检查它们的类型后,我们知道a属于类'int',b属于类'float',c属于类'complex'。
在这里,我们需要处理浮点数,所以让我们列出从数字中去掉小数的不同方法。
- 使用
trunc()
函数 - 使用
int()
- 使用
split()
让我们详细讨论每种方法-
使用trunc()
函数
在第一个程序中,我们将使用trunc()
函数并去掉数字中的小数部分。
以下程序演示了相同的内容-
import math
num_value1 = math.trunc(523.771)
print (num_value1)
print (type(num_value1))
num_value2 = math.trunc(21.67)
print (num_value2)
print (type(num_value2))
num_value3 = math.trunc(182.33)
print (num_value3)
print (type(num_value3))
num_value4 = math.trunc(211.54)
print (num_value4)
print (type(num_value4))
num_value5 = math.trunc(19.1)
print (num_value5)
print (type(num_value5))
输出:
523
<class 'int'>
21
<class 'int'>
182
<class 'int'>
211
<class 'int'>
19
<class 'int'>
解释:
让我们来看看上面程序的解释-
- 由于我们要使用
trunc()
函数,我们导入了math模块。 - 我们提供了五个不同的小数值给五个变量,并在它们传递到
trunc()
函数后检查它们的类型。 - 执行程序后,它会显示所需的输出。
使用int()
现在是时候了解第二种方法,即使用int()
去掉小数部分。
下面的程序显示了如何执行-
num_value1 = 523.771
num_value2 = 21.67
num_value3 = 182.33
print (type(num_value1))
print (type(num_value2))
print (type(num_value3))
new_value1 = int(num_value1)
new_value2 = int(num_value2)
new_value3 = int(num_value3)
print (new_value1)
print (new_value2)
print (new_value3)
print (type(new_value1))
输出:
<class 'float'>
<class 'float'>
<class 'float'>
523
21
182
<class 'int'>
解释:
让我们了解我们在这里做了什么-
- 在第一步,我们为三个变量提供了浮点值并检查了它们的类型。
- 然后,我们将每个变量传递给
int()
并将它们存储到一个新变量中。 - 最后,我们打印存储在这些变量中的值。
- 执行此程序后,将显示所期望的输出。
使用split()
最后,在最后的方法中,我们将使用有趣的split()
来获取整数值。
以下程序演示了相同的内容-
num_values=[523.771,21.67,182.33,211.54,19.1]
sp_lst = []
for ele in num_values:
sp_lst.append(str(ele).split('.')[0])
res_list = [int(i) for i in sp_lst]
print("The resultant list is: ",res_list)
输出:
The resultant list is: [523, 21, 182, 211, 19]
解释:
让我们来看看上面程序的解释-
- 在第一步,我们创建了一个包含所有小数值的列表。
- 然后,我们声明了一个空列表并将这些值附加到其中。
- 接下来,我们从该列表中取出每个元素并将其传递给
int()
。 - 最后,我们显示包含没有小数的数字的结果列表。
结论
在本教程中,我们从Python中使用的数字类型的一般概念开始,然后学习了从数字中去除小数的各种方法。