How to fix floating point decimal to two places even if number is 2.00000

517 Views Asked by At

This is what I have:
x = 2.00001

This is what I need:
x = 2.00

I am using:
float("%.2f" % x)

But all I get is:
2

How can I limit the decimal places to two AND make sure there are always two decimal places even if they are zero?
Note: I do not want the final output to be a string.

5

There are 5 best solutions below

2
ErikR On

This works:

'%.2f" % float(x)

Previously I answered with this:

How about this?

def fmt2decimals(x):
  s = str(int(x*100))
  return s[0:-2] + '.' + s[-2:]

AFAIK you can't get trailing zeros with a format specification like %.2f.

0
obvious On

If you can use decimal (https://docs.python.org/2/library/decimal.html) instead of float:

from decimal import Decimal
Decimal('7').quantize(Decimal('.01'))

quantize() specifies where to round to.

https://docs.python.org/2/library/decimal.html#decimal.Decimal.quantize

0
Jake Griffin On

Have you taken a look at the decimal module? It allows you to do arithmetic while maintaining the proper precision:

>>> from decimal import Decimal
>>> a = Decimal("2.00")
>>> a * 5
Decimal('10.00')
>>> b = Decimal("0.05")
>>> a * b
Decimal('0.1000')
5
isosceleswheel On

Python also has a builtin "round" function: x = round(2.00001, 2) I believe is the command you would use.

0
jyapayne On

Well, in Python, you can't really round to two zeroes without the result being a string. Python will usually always round to the first zero because of how floating point integers are stored. You can round to two digits if the second digit is not zero, though.

For example, this:

round(2.00001, 2)
#Output: 2.0

vs this:

round(2.00601, 2)
#Output: 2.01