问题
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