当前位置: 代码网 > it编程>前端脚本>Python > python保留小数点位数的多种方式(附demo)

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

2024年06月12日 Python 我要评论
前言在python中,保留小数点后特定位数可以通过多种方式实现以下是几种常见的方法,并附上相应的代码示例:使用字符串格式化(string formatting)使用round()函数使用decimal

前言

在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保留小数点位数内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com