如何在Python中舍入一个数字,包括0

时间:2016-11-02 21:54:01

标签: python

如何将数字向上舍入到小数点后两位,包括 例如,1.599应该向上舍入1.60而不是1.6

3 个答案:

答案 0 :(得分:2)

您可以使用%f的字符串格式设置为:

>>> '%.2f' % 1.599
'1.60'

或者,使用str.format()作为:

>>> "{0:.2f}".format(1.599)
'1.60'

注意:此值为str类型。如果你将它输入到float,你将会丢失尾随的0s

答案 1 :(得分:1)

使用%str.format()将数字转换为字符串,并在此过程中对其进行格式化:

"%.2f" % 1.599
"{:.2f}".format(1.599)

答案 2 :(得分:0)

如果舍入" up"这个问题含糊不清。或者只是四舍五入。如果暗示第一个,那么可以做:

    if (!String.prototype.repeat) {
      String.prototype.repeat = function(count) {
        'use strict';
        if (this == null) {
          throw new TypeError('can\'t convert ' + this + ' to object');
        }
        var str = '' + this;
        count = +count;
        if (count != count) {
          count = 0;
        }
        if (count < 0) {
          throw new RangeError('repeat count must be non-negative');
        }
        if (count == Infinity) {
          throw new RangeError('repeat count must be less than infinity');
        }
        count = Math.floor(count);
        if (str.length == 0 || count == 0) {
          return '';
        }
        // Ensuring count is a 31-bit integer allows us to heavily optimize the
        // main part. But anyway, most current (August 2014) browsers can't handle
        // strings 1 << 28 chars or longer, so:
        if (str.length * count >= 1 << 28) {
          throw new RangeError('repeat count must not overflow maximum string size');
        }
        var rpt = '';
        for (;;) {
          if ((count & 1) == 1) {
            rpt += str;
          }
          count >>>= 1;
          if (count == 0) {
            break;
          }
          str += str;
        }
        // Could we try:
        // return Array(count + 1).join(this);
        return rpt;
      }
    }