根据数字的大小在f字符串中显示不同的小数位数?

目标是使用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
elsawin2012 回答:根据数字的大小在f字符串中显示不同的小数位数?

尽管它不能直接插入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}"
,

如果我正确理解了该问题,则可以在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:,}"
本文链接:https://www.f2er.com/3031717.html

大家都在问