Limiting floats to two decimal points

2018-12-31 00:48发布

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.

20条回答
还给你的自由
2楼-- · 2018-12-31 01:43

The method I use is that of string slicing. It's relatively quick and simple.

First, convert the float to a string, the choose the length you would like it to be.

float = str(float)[:5]

In the single line above, we've converted the value to a string, then kept the string only to its first four digits or characters (inclusive).

Hope that helps!

查看更多
骚的不知所云
3楼-- · 2018-12-31 01:44

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

In floating point 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 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("{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 as in currency 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.

查看更多
步步皆殇っ
4楼-- · 2018-12-31 01:46

The built-in round() works just fine in Python 2.7 or later.

Example:

>>> round(14.22222223, 2)
14.22

Check out the documentation.

查看更多
千与千寻千般痛.
5楼-- · 2018-12-31 01:47
orig_float = 232569 / 16000.0

14.5355625

short_float = float("{:.2f}".format(orig_float)) 

14.54

查看更多
人间绝色
6楼-- · 2018-12-31 01:49

You can modify the output format:

>>> a = 13.95
>>> a
13.949999999999999
>>> print "%.2f" % a
13.95
查看更多
流年柔荑漫光年
7楼-- · 2018-12-31 01:49

As @Matt pointed out, Python 3.6 provides f-strings, and they can also use nested parameters:

value = 2.34558
precision = 2
width = 4

print(f'result: {value:{width}.{precision}f}')

which will display result: 2.35

查看更多
登录 后发表回答