【问题标题】:Display different numbers of decimals in an f-string depending on number's magnitude?根据数字的大小在 f 字符串中显示不同的小数位数?
【发布时间】:2020-03-21 11:22:31
【问题描述】:

目标是使用 f 字符串根据数字的大小将浮点数舍入到不同的小数位数。

是否存在类似于以下函数的内联 f 字符串格式?

def number_format(x: float):
    if abs(x) < 10:
        return f"{x:,.2f}"  # thousands seperator for consistency
    if abs(x) < 100:
        return f"{x:,.1f}"
    return f"{x:,.0f}"  # this is the only one that actually needs the thousands seperator

【问题讨论】:

  • 请问您为什么要这样做?
  • 您是在不使用任何函数的情况下尝试这样做,还是可以使用仅计算精度并在 f 字符串中使用该输出的函数?
  • @AlexanderCécile 为什么要这样做?显示没有多余精度的距离。 0.25 公里对我来说是有意义的,而 1,234.25 公里将与 1,234 公里一样准确
  • @JackFleeting 我问这个问题是为了检查是否有内置的方法可以做到这一点,这样我就不必依赖我自己的函数:如果它在标准库中,我更喜欢使用它。
  • @cjm 有道理。不幸的是,我不知道有更好的方法来做到这一点:/至少你可以在 f-string 中调用函数,所以它可能会更糟。

标签: python python-3.6 string-formatting number-formatting f-string


【解决方案1】:

虽然它不能嵌入到 f 字符串中,但以下是一个通用的数字舍入格式化程序,它没有硬编码为在小数点右侧最多有两位数 (与问题中的示例代码不同)。

def number_format(x: float, d: int) -> str:
    """
    Formats a number such that adding a digit to the left side of the decimal
    subtracts a digit from the right side
    :param x: number to be formatter
    :param d: number of digits with only one number to the left of the decimal point
    :return: the formatted number
    """
    assert d >= 0, f"{d} is a negative number and won't work"
    x_size: int = 0 if not x else int(log(abs(x), 10))  # prevent error on x=0
    n: int = 0 if x_size > d else d - x_size  # number of decimal points
    return f"{x:,.{n}f}"

【讨论】:

    【解决方案2】:

    如果我正确理解了这个问题,在python-3.x 你可以这样做

    value = 10000
    print(f'{value:,}')  # prints 10,000
    

    python-2.x

    print('{:,}'.format(value))  # prints 10,000
    

    对于舍入部分你可以做

    def number_format(x: float):
        if abs(x) < 10:
            x = round(x, 2)
            return f"{x:,}"  # thousands seperator for consistency
        if abs(x) < 100:
            x = round(x, 1)
            return f"{x:,}"
        return f"{x:,}"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 2011-09-23
      • 1970-01-01
      • 1970-01-01
      • 2012-12-06
      • 1970-01-01
      • 2015-11-01
      相关资源
      最近更新 更多