【问题标题】:Python format functionPython 格式化函数
【发布时间】:2016-05-26 06:19:46
【问题描述】:

我有一个值格式化程序

def formatter(value):
    return '{:.8f}'.format(value)

但不是总是返回到小数点后 8 位,我想返回到最多 8 位小数。

input                 |     desired_output
100                   |          100
100.01                |         100.01
3.1232342341312323434 |       3.12323423

我该怎么做? 这适用于大量数字。然后,在数字不断超出 dba 设置的限制时,它会被吸入 sql 服务器。

谢谢

【问题讨论】:

  • round(3.1232342341312323434, 8) 可能更适合将浮点数舍入以传递给固定精度的数字。
  • 亲爱的 KillerSnail,我的解决方案是否有助于解决您的问题?

标签: python string format


【解决方案1】:

回答您的问题:

只需使用浮动演示类型'{:g}' 代替'{:f}',如Format Specification Mini-Language 中所述。这会自动丢弃尾随零。此外,如果需要,它会切换为指数表示法。

def formatter(value):
    return "{:^14.8g}".format(value)

l = [100, 100.01, 3.1232342341312323434,
     0.000000000000123, 1234567899.999]

for x in l:
    print(formatter(x))

输出:

     100      
    100.01    
  3.1232342   
   1.23e-13   
1.2345679e+09 

格式化程序功能的一些可能有用的扩展

稍微更改格式化函数,以便在调用时设置打印字段的精度和宽度:

def formatter(value, precision, width):
    return "{{:^{}.{}g}}".format(width, precision).format(value)

l = [100, 100.01, 3.1232342341312323434,
     0.000000000000123, 1234567899.999]

for x in l:
    print(formatter(x, 5, 20))

输出:

             100              
            100.01            
            3.1232            
           1.23e-13           
          1.2346e+09          

我在这个页面上找到了关于Pandas Formatting Snippets的嵌套format()函数

【讨论】:

    【解决方案2】:

    你可以这样做:

    '{:^<stringwidth>.8f}'.format(value).rstrip('0').rstrip('.')
    

    其中 stringwidth 是所需输出的宽度,其中值应居中。

    【讨论】:

      【解决方案3】:

      如果stringwidth 大于构成数字的字符数,则第一个解决方案不起作用,因为它会在字符串周围添加空格,而rstrip 没有任何效果。

      为了让它工作,首先你应该把它弄圆(必要时剥去),然后,作为第二步 - 将它居中。因此,我们有:

      numbers = [100, 100.01, 3.1232342341312323434]
      
      for number in numbers:
          rounded_number = '{:.8f}'.format(i).rstrip('0').rstrip('.')
          centered_number = '{:^14}'.format(rounded_number)  # substitute 14 with the desired width
          print (centered_number)
      
          # Or, as a one-liner
          # print ('{:^14}'.format('{:.8f}'.format(i).rstrip('0').rstrip('.')))
      

      输出:

           100      
          100.01    
        3.12323423  
      

      【讨论】:

        猜你喜欢
        • 2021-08-25
        • 1970-01-01
        • 2022-12-06
        • 2016-04-07
        • 1970-01-01
        • 2012-02-14
        • 1970-01-01
        • 2018-08-31
        • 1970-01-01
        相关资源
        最近更新 更多