• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python如何保留指定小数点位数?

python 搞java代码 3年前 (2022-05-21) 23次浏览 已收录 0个评论

python保留指定小数点位数的方法:

1、使用’%.2f’ %f 方法

f = 1.23456

<a href="https://www.gaodaima.com/tag/print" title="查看更多关于print的文章" target="_blank">print</a>('%.4f' % f)
print('%.3f' % f)
print('%.2f' % f)

www#gaodaima.com来源gaodai$ma#com搞$$代**码)网搞代码

结果:

1.2346
1.235
1.23

这个方法会进行四舍五入

2、format函数

Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。

基本语法是通过 {} 和 : 来代替以前的 % 。

print(format(1.23456, '.2f'))
print(format(1.23456, '.3f'))
print(format(1.23456, '.4f'))

输出结果:

1.23
1.235
1.2346

3、round()函数

round() 方法返回浮点数x的四舍五入值。

以下是 round() 方法的语法:

round( x [, n]  )

参数:

x — 数值表达式。

n — 数值表达式。

a = 1.23456
b = 2.355
c = 3.5
d = 2.5
print(round(a, 3))
print(round(b, 2))
print(round(c))
print(round(d))

输出结果:

1.235   # 1.23456最终向前进位了
2.35    # 2.355居然没进位
4       # 最终3.5居然变为4了
2       # 最终2.5取值变为2

更多Python知识请关注云海天Python教程栏目。

来源:搞代码网:原文地址:https://www.gaodaima.com


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python如何保留指定小数点位数?

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址