翼度科技»论坛 编程开发 python 查看内容

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

6

主题

6

帖子

18

积分

新手上路

Rank: 1

积分
18
前言

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

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

1. 字符串格式

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

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

  2. value = Decimal('3.141592653589793')
  3. rounded_value = value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
  4. print(rounded_value)  # 输出: 3.14
复制代码
4. numpy库

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

  2. value = 3.141592653589793
  3. rounded_value = np.round(value, 2)
  4. print(rounded_value)  # 输出: 3.14
复制代码
5. Demo

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

  3. value = 3.141592653589793

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

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

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

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

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

  20. # 使用numpy库
  21. rounded_value_numpy = np.round(value, 2)
  22. print(f"numpy库: {rounded_value_numpy}")
复制代码
截图如下:

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

来源:https://www.jb51.net/python/3221089eb.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具