将浮点数限制为两位小数 [英] Limiting floats to two decimal points

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

问题描述

我希望 a 被四舍五入为 13.95.

<预><代码>>>>一种13.949999999999999>>>回合(a, 2)13.949999999999999

round 函数没有按照我预期的方式工作.

解决方案

您遇到了老问题 带有浮点数,并非所有数字都可以精确表示.命令行只是从内存中向您显示完整的浮点形式.

使用浮点表示,您的四舍五入版本是相同的数字.由于计算机是二进制的,它们将浮点数存储为整数,然后将其除以 2 的幂,因此 13.95 将以类似于 125650429603636838/(2**53) 的方式表示.

双精度数的精度为 53 位(16 位),常规浮点数的精度为 24 位(8 位).Python 中的浮点类型使用双精度来存储值.

例如

<预><代码>>>>125650429603636838/(2**53)13.949999999999999>>>234042163/(2**24)13.949999988079071>>>a = 13.946>>>打印(一)13.946>>>打印(%.2f"%a)13.95>>>回合(a,2)13.949999999999999>>>打印(%.2f"%轮(a,2))13.95>>>打印({:.2f}".格式(一))13.95>>>打印("{:.2f}".format(round(a, 2)))13.95>>>打印("{:.15f}".format(round(a, 2)))13.949999999999999

如果您只需要两位小数(例如显示货币价值),那么您有几个更好的选择:

  1. 使用整数并以美分(而不是美元)存储值,然后除以 100 以转换为美元.
  2. 或者使用诸如十进制之类的定点数.

I want a to be rounded to 13.95.

>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999

The round function does not work the way I expected.

解决方案

You are running into the old problem with floating point numbers that not all numbers can be represented exactly. The command line is just showing you the full floating point form from memory.

With floating point representation, your rounded version is the same number. Since computers are binary, they store floating point numbers as an integer and then divide it by a power of two so 13.95 will be represented in a similar fashion to 125650429603636838/(2**53).

Double precision numbers have 53 bits (16 digits) of precision and regular floats have 24 bits (8 digits) of precision. The floating point type in Python uses double precision to store the values.

For example,

>>> 125650429603636838/(2**53)
13.949999999999999

>>> 234042163/(2**24)
13.949999988079071

>>> a = 13.946
>>> print(a)
13.946
>>> print("%.2f" % a)
13.95
>>> round(a,2)
13.949999999999999
>>> print("%.2f" % round(a, 2))
13.95
>>> print("{:.2f}".format(a))
13.95
>>> print("{:.2f}".format(round(a, 2)))
13.95
>>> print("{:.15f}".format(round(a, 2)))
13.949999999999999

If you are after only two decimal places (to display a currency value, for example), then you have a couple of better choices:

  1. Use integers and store values in cents, not dollars and then divide by 100 to convert to dollars.
  2. Or use a fixed point number like decimal.

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

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