【问题标题】:python fixed digits roundingpython固定数字舍入
【发布时间】:2020-06-02 10:20:04
【问题描述】:

python 2 中有没有可以做到这一点的函数?

1234 -> round(1234, 2) = 1200
1234 -> round(1234, 3) = 1230
12.34 -> round(12.34, 3) = 12.3

基本上第二个数字表示数字的精度,后面的一切都应该四舍五入。

根据我想出的评论:

def round_to_precision(x, precision):
    return int(round(x / float(10 ** precision))) * 10 ** precision

但这仍然是错误的,因为我不知道数字的大小。

【问题讨论】:

  • 检查this 网站。该算法适用于所有数字
  • 谢谢。我做了修改,但还是有问题。

标签: python python-2.7


【解决方案1】:

这是一个解决方案(为清楚起见,逐步编写)。

import math

num_digits = lambda x: int((math.log(x, 10)) + 1)

def round(x, precision): 
    digits = num_digits(x) 
    gap = precision - digits
    x = x * (10 ** gap)
    x = int(x) 
    x = x / (10 ** gap)
    return x

结果:

round(1234, 2) # 1200
round(1234, 3) # 1230
round(12.34, 3) # 12.3

【讨论】:

    【解决方案2】:

    我找到了解决办法:

    def round_to_precision(x, precision):
        fmt_string = '{:.' + str(precision) + 'g}'
        return float(fmt_string.format(x))
    
    
    print round_to_precision(1234, 2)
    print round_to_precision(1234, 3)
    print round_to_precision(12.34, 3)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多