Display different numbers of decimals in an f-string depending on number's magnitude?

风格不统一 提交于 2019-12-11 14:48:45

问题


The goal is to use an f-string to round a float to a different number of decimal places based on the size of the number.

Is there in-line f-string formatting that works like the following function?

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

回答1:


Although it is not something that can go in-line in an f-string, the following is a generic number rounding formatter that isn't hard-coded to have a maximum of two digits to the right of the decimal point (unlike the example code in the question).

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:


If I understood the question correctly, in python-3.x you can do

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

and in python-2.x,

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

For the rounding part you can do

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://stackoverflow.com/questions/59044185/display-different-numbers-of-decimals-in-an-f-string-depending-on-numbers-magni

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!