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

在Python中,保留小数点后特定位数可以通过多种方式实现,以下是几种常见的方法,并附上相应的代码示例,使用字符串格式化,使用round()函数,使用Decimal模块和使用numpy库,文中通过代码讲解的非常详细,需要的朋友可以参考下

前言
在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
  1. round函数
value = 3.141592653589793
rounded_value = round(value, 2)
print(rounded_value)  # 输出: 3.14
  1. 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
  1. numpy库
    大量的数值计算,使用numpy库是个好选择
import numpy as np
 
value = 3.141592653589793
rounded_value = np.round(value, 2)
print(rounded_value)  # 输出: 3.14
  1. 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保留小数点位数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持vb.net教程C#教程python教程SQL教程access 2010教程Visual Basic 2010 2012 2013 从入门到精通|xin3721自学网

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值