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