获取多个数字
我一直在寻找一种在 python 中只获取十进制数逗号右侧 4 位数字的方法,但我找不到。看了这篇文章,---> 使用新的 Python 格式函数对小数进行四舍五入 ,但是那里写的函数...
>>> n = 4
>>> p = math.pi
>>> '{0:.{1}f}'.format(p, n)
'3.1416'
...似乎不适用于我的情况。
我导入了模块“数学”和“小数”,但也许我缺少其他一些要导入的模块,但我不知道要导入哪些模块。
谢谢大家,如果这个问题已经发布,我们深表歉意。
佩克斯
I've been searching for a way in python to get only 4 digits on the right of the comma of a decimal number, but i couldn't find. Took a look on this post,---> Rounding decimals with new Python format function
,but the function written there...
>>> n = 4
>>> p = math.pi
>>> '{0:.{1}f}'.format(p, n)
'3.1416'
...seems not to work in my case.
I imported the modules "math" and "decimal", but maybe i'm missing some others to import, but i don't know which of them to import.
Thanks everyone, and sorry if this issue has already been posted.
Peixe
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我知道它使用旧语法,但我个人更喜欢它。
I know its using the old syntax but I personally prefer it.
你所拥有的很好(将5舍入到6)
如果你想要截断而不是四舍五入,你可以这样做:
输出:
3.14159265359
3.1415
3.1415
What you have is fine (rounding the 5 up to a 6)
If you want truncation instead of rounding you could go:
output:
3.14159265359
3.1415
3.1415
如果您只需要浮点数的其余部分,可以将其转换为字符串并按
'.'
:或
decimal.Decimal
分割:If you only want the remainder of a float you could convert to a string and split on
'.'
:or
decimal.Decimal
: