如果数字是2.00000,如何将浮点小数修复为两个位置

时间:2015-08-07 17:47:46

标签: python numbers format decimal floating-point-precision

这就是我所拥有的:
    x = 2.00001

这就是我需要的:
    x = 2.00

我正在使用:
    float("%.2f" % x)

但我得到的只是:
    2

如何将小数位数限制为2并确保总共有两位小数,即使它们为零? 注意:我不希望最终输出为字符串。

5 个答案:

答案 0 :(得分:0)

这有效:

'%.2f" % float(x)

之前我回答过这个问题:

这个怎么样?

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

AFAIK您无法使用%.2f等格式规范获得尾随零。

答案 1 :(得分:0)

如果你可以使用十进制(https://docs.python.org/2/library/decimal.html)而不是float:

public class Board {

    private Map<2DPoint,Ship> ships;

    public Board () {
       this.ships = new HashMap<> ();
    }
    public addShip (2DPoint where, Ship ship) {
       this.ships.put(where,ship);
    }
    public moveShip (2DPoint from,2DPoint to) {
       Ship shipToMove = this.ships.get(from);
       if (shipToMove == null) {
           throw new IllegalArgumentException("There is no ship at " + from);
       }
       this.ships.put(from,null); // empty the previous cell
       this.ships.put(to,shipToMove); // assign to the new cell the ship.
    }

quantize()指定要舍入的位置。

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

答案 2 :(得分:0)

您是否看过decimal模块?它允许您在保持适当精度的同时进行算术运算:

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

答案 3 :(得分:0)

Python还有一个内置的“圆形”功能:x = round(2.00001, 2)我相信你将使用的命令。

答案 4 :(得分:0)

好吧,在Python中,你不能真正舍入到两个零,而结果不是字符串。由于存储浮点整数的方式,Python通常会循环到第一个零。如果第二个数字为零,则可以舍入到两位数。

例如,这个:

round(2.00001, 2)
#Output: 2.0

vs this:

round(2.00601, 2)
#Output: 2.01