Python - 将浮点数舍入为 2 位数 [英] Python - round a float to 2 digits

查看:86
本文介绍了Python - 将浮点数舍入为 2 位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个浮点变量四舍五入为 2 位有效数字并将结果存储到一个新变量中(或与之前相同,没关系),但这就是发生的情况:

<预><代码>>>>一种981.32000000000005>>>b=轮(a,2)>>>乙981.32000000000005

我需要这个结果,但是到一个不能是字符串的变量中,因为我需要将它作为浮点数插入...

<预><代码>>>>打印 b981.32

实际上 truncate 也可以工作,在这种情况下我不需要极端的精度.

解决方案

你想要做的实际上是不可能的.那是因为 981.32 不能完全表示为二进制浮点值.最接近的双精度二进制浮点值是:

981.3200000000000500222085975110530853271484375

我怀疑这可能会让您感到震惊.如果是这样,那么我建议您阅读 每个计算机科学家应该了解的关于浮点运算的知识.

您可以选择通过以下方式之一解决您的问题:

  1. 接受二进制浮点数不能准确表示这些值,并继续使用它们.根本不做任何四舍五入,并保留完整值.如果您希望将值显示为文本,请对其进行格式化,以便只显示两位小数.
  2. 使用可以准确表示您的号码的数据类型.这意味着十进制而不是二进制类型.在 Python 中,您将使用 decimal.

I would need to have a float variable rounded to 2 significant digits and store the result into a new variable (or the same of before, it doesn't matter) but this is what happens:

>>> a    
981.32000000000005    
>>> b= round(a,2)    
>>> b
981.32000000000005

I would need this result, but into a variable that cannot be a string since I need to insert it as a float...

>>> print b    
981.32

Actually truncate would also work I don't need extreme precision in this case.

解决方案

What you are trying to do is in fact impossible. That's because 981.32 is not exactly representable as a binary floating point value. The closest double precision binary floating point value is:

981.3200000000000500222085975110530853271484375

I suspect that this may come as something of a shock to you. If so, then I suggest that you read What Every Computer Scientist Should Know About Floating-Point Arithmetic.

You might choose to tackle your problem in one of the following ways:

  1. Accept that binary floating point numbers cannot represent such values exactly, and continue to use them. Don't do any rounding at all, and keep the full value. When you wish to display the value as text, format it so that only two decimal places are emitted.
  2. Use a data type that can represent your number exactly. That means a decimal rather than binary type. In Python you would use decimal.

这篇关于Python - 将浮点数舍入为 2 位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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