在Python中,获取小数结果可以通过以下几种方法:
1. 使用`round()`函数:
四舍五入到指定小数位数
rounded_value = round(3.14159, 2)
print(rounded_value) 输出:3.14
2. 使用格式化字符串(`%`操作符或`.format()`方法):
使用%操作符
formatted_value = "%.2f" % 3.14159
print(formatted_value) 输出:3.14
使用.format()方法
formatted_value = "{:.2f}".format(3.14159)
print(formatted_value) 输出:3.14
3. 使用`decimal`模块进行精确计算:
from decimal import Decimal
将浮点数转换为Decimal类型
decimal_value = Decimal('3.14159')
设定有效数字,限定结果样式
getcontext().prec = 6
四舍五入,保留几位小数
quantized_value = decimal_value.quantize(Decimal('0.00'))
print(quantized_value) 输出:Decimal('3.14')
Decimal结果转化为string
str_value = str(quantized_value)
print(str_value) 输出:'3.14'
4. 使用`math`模块的`floor()`和`modf()`函数:
import math
取小数的整数部分
integer_part = math.floor(3.14159)
print(integer_part) 输出:3
使用modf()函数同时取小数的整数部分和小数部分
integer_part, decimal_part = math.modf(3.14159)
print(integer_part) 输出:0.14159
print(decimal_part) 输出:3.0
以上方法可以根据具体需求选择使用