打印浮点数时如何防止打印功能自动舍入? [英] How to prevent automatic rounding in print function when printing a float number?

查看:68
本文介绍了打印浮点数时如何防止打印功能自动舍入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑一下这种情况:

Let's consider this situation:

from math import sqrt

x = sqrt(19) # x : 4.358898943540674

print("{:.4f}".format(x))
# I don't want to get 4.3589
# I want to get 4.3588

print()函数自动将数字四舍五入,但是我不希望这样.我该怎么办?

The print() function rounds the number automatically, but I don't want this. What should I do?

推荐答案

如果您想将数字向下舍入到小数点后第四位,而不是将其舍入到最接近的可能性,则可以四舍五入.

If you want to round the number down to the 4th decimal place rather than round it to the nearest possibility, you could do the rounding yourself.

x = int(x * 10**4) / 10**4
print("{:.4f}".format(x))

这给你

4.3588

乘以并随后除以10**4会将数字移位小数点后4位,并且int函数舍入为整数.将它们全部组合即可实现您想要的.由于浮点问题,有些边缘情况会产生意想不到的结果,但是这种情况很少见.

Multiplying and later dividing by 10**4 shifts the number 4 decimal places, and the int function rounds down to an integer. Combining them all accomplishes what you want. There are some edge cases that will give an unexpected result due to floating point issues, but those will be rare.

这篇关于打印浮点数时如何防止打印功能自动舍入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆