Python3 里面的四舍五入

目录

1.一般的四舍五入 : 使用内置的round函数

1.1官方文档:

1.2 举例说明:

2.python3里的格式化输出 format

2.1 记忆法则 :填齐宽 逗精类

2.2 format实质就是通过设置精度间接使用了等效round函数,但是不要把格式化输出和四舍五入函数搞混了。

3.数据分析时:numpy数组的四舍五入


1.一般的四舍五入 : 使用内置的round函数

1.1官方文档:

1.2 举例说明:

print(round(1.23))  			# 1
print(type(round(1.23)))		# <class 'int'>
	
print(round(1.23, 0))			# 1.0
print(type(round(1.23, 0)))		# <class 'float'>

print(round(1.23, 1))			# 1.2
print(type(round(1.23, 1)))		# <class 'float'>

print(round(1.27, 1))			# 1.3
print(type(round(1.27, 1)))		# <class 'float'>

print(round(-1.27, 1))			# -1.3
print(type(round(-1.27, 1)))	# <class 'float'>

print(round(3.1415, 3))			# 3.142
print(type(round(3.1415, 3)))	# <class 'float'>

2.python3里的格式化输出 format

2.1 记忆法则 :填齐宽 逗精类

2.2 format实质就是通过设置精度间接使用了等效round函数,但是不要把格式化输出和四舍五入函数搞混了。

x = 3.1415926
print(format(x, '5.2f'))
print(format(x, '4.0f'))
print(format(x, '6.3f'))
print(format(x, '3.3f'))
print(format(x, '0.3f'))
print('value is {:0.4f}'.format(x))

        输出结果:

 

3.数据分析时:numpy数组的四舍五入

import numpy as np
a = np.array([1.136, 2.317, 2.65964, 123.3356, 4.61475])
print(np.round(a))
print(np.round(a, decimals=1))
print(np.round(a, decimals=2))
print(np.round(a, decimals=-1))

输出结果:

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值