Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

python - 将浮点数限制为两位小数(Limiting floats to two decimal points)

I want a to be rounded to 13.95 .

(我希望将a舍入为13.95 。)

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

The round function does not work the way I expected.

(round功能不能按我预期的方式工作。)

  ask by translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).

(由于计算机是二进制的,因此它们将浮点数存储为整数,然后将其除以2的幂,因此将以与125650429603636838 /(2 ** 53)相似的方式表示13.95。)

Double precision numbers have 53 bits (16 digits) of precision and regular floats have 24 bits (8 digits) of precision.

(双精度数字的精度为53位(16位),常规浮点数的精度为24位(8位)。)

The floating point type in Python uses double precision to store the values.

(Python中浮点类型使用双精度来存储值。)

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("{0:.2f}".format(a))
  13.95
  >>> print("{0:.2f}".format(round(a,2)))
  13.95
  >>> print("{0:.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.

    (使用整数并以美分而不是美元存储值,然后除以100转换为美元。)

  2. Or use a fixed point number like decimal .

    (或者使用定点数,例如小数 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...