【问题标题】:Python, want to print float in exact format +-00.00Python,想要以精确的格式打印浮点数 +-00.00
【发布时间】:2012-01-31 21:58:49
【问题描述】:

我需要将浮点数格式化为 +-00.00 格式,尝试了基本的字符串格式化,但如果值为小数,则无法获取前导 + 或 - 符号或两个前导 0,是否有指针?

【问题讨论】:

    标签: python printing floating-point


    【解决方案1】:

    '%+06.2f' % 1.1123344

    + means always use sign
    0 means zero fill to full width.
    6 is the total field width including sign and decimal point
    .2 means 2 decimals.
    f is float
    

    【讨论】:

      【解决方案2】:

      使用'%+06.2f' 适当地设置宽度和精度。使用新式格式字符串的等价物是 '{:+06.2f}'.format(n)(如果您的 Python 版本需要位置组件,则为 '{0:+06.2f}')。

      【讨论】:

        【解决方案3】:

        使用这个应该可以做到

        x = 50.4796
        a = -50.1246
        
        print " %+2.2f" % (x)
        print " %+2.2f" % (a)
        

        应打印以下内容

        +50.48
        -50.12
        

        【讨论】:

          猜你喜欢
          • 2012-07-14
          • 1970-01-01
          • 2021-07-25
          • 2011-03-14
          • 1970-01-01
          • 2020-08-04
          • 1970-01-01
          • 1970-01-01
          • 2021-05-15
          相关资源
          最近更新 更多