【问题标题】:Fixed digits after decimal with f-strings使用 f 字符串固定小数点后的数字
【发布时间】:2025-12-15 05:35:01
【问题描述】:

有没有简单的方法用 Python f-strings 来固定小数点后的位数? (特别是 f 字符串,而不是其他字符串格式化选项,如 .format 或 %)

例如,假设我想显示小数点后 2 位。

我该怎么做?这么说吧

a = 10.1234

【问题讨论】:

    标签: python python-3.x f-string


    【解决方案1】:

    在格式表达式中包含类型说明符:

    >>> a = 10.1234
    >>> f'{a:.2f}'
    '10.12'
    

    【讨论】:

    • 我发现的 f 字符串格式示例(包括 PEP)都没有显示您可以使用类型说明符。我想我应该这样认为,但是把它叫出来的文档会很好。
    • 你是对的,大多数示例都没有格式说明符。在 PEP 中,十六进制示例是:f'input={value:#06x}',而日期时间示例是:{anniversary:%A, %B %d, %Y}{date:%A}。我认为关键的解释在Code Equivalence 部分。
    • 哦,伙计,这是华丽而简单的。为什么我花了整整 45 秒才找到这个答案?加油,谷歌。
    • 还要注意,如果没有 f,如果你写 - f'{a:.2}',它将计算总位数,答案将为 10
    • @tarabyte - f-strings 是在 3.6 中引入的。该语法在 3.5.2 docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498 中不存在
    【解决方案2】:

    当涉及到float 号码时,您可以使用format specifiers

    f'{value:{width}.{precision}}'
    

    地点:

    • value 是任何计算结果为数字的表达式
    • width 指定要显示的总字符数,但如果 value 需要的空间比宽度指定的多,则使用额外的空间。
    • precision 表示小数点后使用的字符数

    您缺少的是十进制值的类型说明符。在这个link 中,您可以找到浮点和十进制的可用表示类型。

    这里有一些示例,使用f(定点)表示类型:

    # notice that it adds spaces to reach the number of characters specified by width
    In [1]: f'{1 + 3 * 1.5:10.3f}'
    Out[1]: '     5.500'
    
    # notice that it uses more characters than the ones specified in width
    In [2]: f'{3000 + 3 ** (1 / 2):2.1f}' 
    Out[2]: '3001.7'
    
    In [3]: f'{1.2345 + 4 ** (1 / 2):9.6f}'
    Out[3]: ' 3.234500'
    
    # omitting width but providing precision will use the required characters to display the number with the the specified decimal places
    In [4]: f'{1.2345 + 3 * 2:.3f}' 
    Out[4]: '7.234'
    
    # not specifying the format will display the number with as many digits as Python calculates
    In [5]: f'{1.2345 + 3 * 0.5}'
    Out[5]: '2.7344999999999997'
    

    【讨论】:

    • @Bouncner no.
    • 我在哪里可以找到哪些类型的回合使用格式说明符方法,谢谢。我知道通过测试它“四舍五入,关系从零开始”,它被称为 ROUND_HALF_UP。我在文档中找不到有关使用格式说明符的回合策略的任何信息。
    【解决方案3】:

    添加到 Robᵩ 的答案:如果您想打印相当大的数字,使用千位分隔符会很有帮助(注意逗号)。

    >>> f'{a*1000:,.2f}'
    '10,123.40'
    

    【讨论】:

    • 谢谢你,高五的逗号 - 没有逗号谁能读懂大数?
    • 我确实想打印大数字。
    【解决方案4】:

    添加到 Rob 的 answer,您可以将格式说明符与 f 字符串 (more here) 一起使用。

    • 您可以控制小数位数
    pi = 3.141592653589793238462643383279
    
    print(f'The first 6 decimals of pi are {pi:.6f}.')
    
    The first 6 decimals of pi are 3.141593.
    
    • 您可以转换为百分比
    grade = 29/45
    
    print(f'My grade rounded to 3 decimals is {grade:.3%}.')
    
    My grade rounded to 3 decimals is 64.444%.
    
    • 您可以执行其他操作,例如打印恒定长度
    from random import randint
    for i in range(5):
        print(f'My money is {randint(0, 150):>3}$')
    
    My money is 126$
    My money is   7$
    My money is 136$
    My money is  15$
    My money is  88$
    
    • 甚至使用逗号千位分隔符打印:
    print(f'I am worth {10000000000:,}$')
    
    I am worth 10,000,000,000$
    

    【讨论】:

      【解决方案5】:
      a = 10.1234
      
      print(f"{a:0.2f}")
      

      0.2f:

      • 0 告诉 python 对总位数没有限制 显示
      • .2 表示我们只想取小数点后 2 位 (结果将与 round() 函数相同)
      • f 表示它是一个浮点数。如果你忘记了 f 那么它只会在小数点后少打印 1 位。在这种情况下,它只会是小数点后一位。

      关于数字 f 字符串的详细视频 https://youtu.be/RtKUsUTY6to?t=606

      【讨论】:

      • 根据文档docs.python.org/3/library/string.html#formatexamples f 代表“定点”,而不是“浮点表示法”>定点表示法。将数字显示为定点数。默认精度为 6。如果您使用 e(似乎是默认值),它将以指数表示法格式化您的浮点数。
      • 您从哪里得知默认精度为 6?
      • @MrR:在他刚刚在同一个评论中写的链接中说。
      • Ty,找到了。对于像我这样受损的人的参考,请在该页面上搜索“没有给出精度,使用小数点后 6 位的精度作为浮点数”以获取“f”“演示文稿类型”。
      【解决方案6】:
      考虑:
      >>> number1 = 10.1234
      >>> f'{number1:.2f}'
      '10.12'
      
      句法:
      "{" [field_name] ["!" conversion] [":" format_spec] "}"
      
      解释:
      # Let's break it down...
      #       [field_name]     => number1
      #       ["!" conversion] => Not used
      #       [format_spec]    => [.precision][type] 
      #                        => .[2][f] => .2f  # where f means Fixed-point notation
      

      更进一步,格式字符串具有以下语法。如您所见,还有很多事情可以做。

      Syntax: "{" [field_name] ["!" conversion] [":" format_spec] "}"
      
      # let's understand what each field means...
          field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*
          arg_name          ::=  [identifier | digit+]
          attribute_name    ::=  identifier
          element_index     ::=  digit+ | index_string
          index_string      ::=  <any source character except "]"> +
          conversion        ::=  "r" | "s" | "a"
          format_spec       ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
      
                  # Looking at the underlying fields under format_spec...
                  fill            ::=  <any character>
                  align           ::=  "<" | ">" | "=" | "^"
                  sign            ::=  "+" | "-" | " "
                  width           ::=  digit+
                  grouping_option ::=  "_" | ","
                  precision       ::=  digit+
                  type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
      

      参考https://docs.python.org/3/library/string.html#format-string-syntax

      【讨论】:

      • 如果我应该包含更多示例,请告诉我...谢谢
      【解决方案7】:

      简单

      a = 10.1234
      print(f"{a:.1f}")
      

      输出:10.1

      a = 10.1234
      print(f"{a:.2f}")
      

      输出:10.12

      a = 10.1234
      print(f"{a:.3f}")
      

      输出:10.123

      a = 10.1234
      print(f"{a:.4f}")
      

      输出:10.1234

      只需更改小数点符号后的值,代表您要打印的小数点。

      【讨论】: