【问题标题】:How could I format a python string from float number with fix length and width我怎么能从浮点数格式化一个python字符串并固定长度和宽度
【发布时间】:2018-12-01 03:53:36
【问题描述】:

假设我的浮点数是12.3456,我需要将它打印为_12.34,这意味着.之前的数字长度是3,而.之后的长度仍然是2。我试过这个'{:.2f}'.format(12.3456),它只给了我12.34,它在数字1之前缩短了一个空格。那么我怎样才能使我的需求成为可能呢?

【问题讨论】:

标签: python string format precision


【解决方案1】:

您可以通过在格式字符串中的句点前放置一个数字来指定渲染字符串的总宽度:

>>> '{:6.2f}'.format(12.3456)
' 12.35'

【讨论】:

    【解决方案2】:

    您可以申请一个额外的.rjust(6)(6 因为 3 + 2 位和一个小数点):

    >>> '{:.2f}'.format(12.3456).rjust(6)
    ' 12.35'
    

    【讨论】:

      【解决方案3】:

      先将浮点数转换为小数点后 2 位然后格式化如何? 例如,如果你想截断它使用 math.floor,或者如果你想四舍五入或者使用十进制模块(导入十进制)python decimal module

      ,则使用 round()

      使用 math.floor 的示例代码:

      import math
      print('{0:_>6}'.format(math.floor(112.345*100)/100)) #112.34
      print('{0:_>6}'.format(math.floor(12.345*100)/100))  #_12.34
      

      【讨论】:

        【解决方案4】:

        添加到@cody 的答案,如果你有python 3.6+,你可以使用f 字符串

        >>> f'{12.3456:6.2f}'
        ' 12.35'
        

        【讨论】:

          猜你喜欢
          • 2012-01-15
          • 1970-01-01
          • 2018-01-28
          • 2011-10-15
          • 2012-02-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多