简体   繁体   English

如何将浮点小数固定为两位,即使数字为2.00000

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

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. 注意:我不希望最终输出为字符串。

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 . 抱歉,您无法使用%.2f类的格式规范获取尾随零。

If you can use decimal ( https://docs.python.org/2/library/decimal.html ) instead of float: 如果您可以使用小数点( https://docs.python.org/2/library/decimal.html )而不是float:

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

quantize() specifies where to round to. Quantize()指定四舍五入到的位置。

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

Have you taken a look at the decimal module? 您看过decimal模块了吗? 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')

Python还具有内置的“舍入”功能: x = round(2.00001, 2)我相信这是您将使用的命令。

Well, in Python, you can't really round to two zeroes without the result being a string. 好吧,在Python中,如果不将结果作为字符串,就不能真正舍入到两个零。 Python will usually always round to the first zero because of how floating point integers are stored. 由于存储浮点整数的方式,Python通常总是四舍五入到第一个零。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM