沈恩惠御承装饰 发表于 2024-6-10 18:07:46

python保留小数点位数的多种方式(附demo)

前言

在Python中,保留小数点后特定位数可以通过多种方式实现
以下是几种常见的方法,并附上相应的代码示例:

[*]使用字符串格式化(String Formatting)
[*]使用round()函数
[*]使用Decimal模块
[*]使用numpy库

1. 字符串格式

方法1:使用f-strings (Python 3.6及以上)
value = 3.141592653589793
formatted_value = f"{value:.2f}"
print(formatted_value)# 输出: 3.14方法2:使用str.format()
value = 3.141592653589793
formatted_value = "{:.2f}".format(value)
print(formatted_value)# 输出: 3.14方法3:使用百分号 (%) 格式化
value = 3.141592653589793
formatted_value = "%.2f" % value
print(formatted_value)# 输出: 3.14
2. round函数

value = 3.141592653589793
rounded_value = round(value, 2)
print(rounded_value)# 输出: 3.14
3. Decimal模块

Decimal模块提供更高的精度和控制,可以精确控制小数点后的位数
from decimal import Decimal, ROUND_HALF_UP

value = Decimal('3.141592653589793')
rounded_value = value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
print(rounded_value)# 输出: 3.14
4. numpy库

大量的数值计算,使用numpy库是个好选择
import numpy as np

value = 3.141592653589793
rounded_value = np.round(value, 2)
print(rounded_value)# 输出: 3.14
5. Demo

总体Demo如下:
import numpy as np
from decimal import Decimal, ROUND_HALF_UP

value = 3.141592653589793

# 使用f-strings
formatted_value_f = f"{value:.2f}"
print(f"f-strings: {formatted_value_f}")

# 使用str.format()
formatted_value_format = "{:.2f}".format(value)
print(f"str.format(): {formatted_value_format}")

# 使用百分号 (%) 格式化
formatted_value_percent = "%.2f" % value
print(f"百分号格式化: {formatted_value_percent}")

# 使用round()函数
rounded_value_round = round(value, 2)
print(f"round(): {rounded_value_round}")

# 使用Decimal模块
decimal_value = Decimal('3.141592653589793')
rounded_value_decimal = decimal_value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
print(f"Decimal模块: {rounded_value_decimal}")

# 使用numpy库
rounded_value_numpy = np.round(value, 2)
print(f"numpy库: {rounded_value_numpy}")截图如下:

到此这篇关于python保留小数点位数的多种方式(附demo)的文章就介绍到这了,更多相关python保留小数点位数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

来源:https://www.jb51.net/python/3221089eb.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: python保留小数点位数的多种方式(附demo)