Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 509
cjm Avatar asked Dec 11 '25 03:12

cjm


1 Answers

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}"
like image 117
cjm Avatar answered Dec 12 '25 18:12

cjm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!