如何用 python 格式化非常小的数字?
How to format very small number with python?
我正在查看加密货币价格。当转换成比特币或有时甚至转换成美元时,我从我使用的 api 中得到的金额非常小。
这是我可以获得的响应类型:
- 7.2e-05
- 4.89686e-07
我是这样做的:
answer_from_api = 7.2e-05
formatting = format(answer_from_api, "f")
print(formatting)
>>>> 0.000072
但是,我想要一个分隔符来让内容更容易阅读,例如:
price = 0.000 072
我希望它适用于像这样的非常小的数字:4.89686e-07 但也不会像 150.22
这样“打破”更大的数字
有什么想法吗?
最好的,
所以,有很多方法可以解决这个问题。我会做的是:
def format_small(x, sep_loc=3):
# check if number is not really small (no 'e' in string representation)
if "e" not in str(x):
# return the string representation
return str(x)
# get the number of decimals
dec = int(str(x).split("-")[1])-1
# for really small numbers add a space at the position indicated by sep_loc
s = format(x, f".{dec+sep_loc-1}f")
return s[:-sep_loc] + ' ' + s[-sep_loc:]
print(format_small(7.2e-05)) # prints 0.000 072
print(format_small(150.21)) # prints 150.21
print(format_small(0.12)) # prints 0.12
print(format_small(4.89686e-07)) # prints 0.00000 049
我认为 format
语言中没有任何内容可以满足此要求,但您可以轻松编写自己的辅助函数。
def format_with_space(number, decimals=6):
as_str = f'{{:.{decimals}f}}'.format(number)
chunks = []
start_chunk = as_str.find('.') + 4
chunks.append(as_str[:start_chunk])
for i in range(start_chunk, len(as_str), 3):
chunks.append(as_str[i:i+3])
return ' '.join(chunks)
print(format_with_space(7.2e-05)) # 0.000 072
print(format_with_space(150.22, decimals=3)) # 150.220
print(format_with_space(7.2e-05, decimals=20)) # 0.000 072 000 000 000 000 00
我正在查看加密货币价格。当转换成比特币或有时甚至转换成美元时,我从我使用的 api 中得到的金额非常小。
这是我可以获得的响应类型:
- 7.2e-05
- 4.89686e-07
我是这样做的:
answer_from_api = 7.2e-05
formatting = format(answer_from_api, "f")
print(formatting)
>>>> 0.000072
但是,我想要一个分隔符来让内容更容易阅读,例如:
price = 0.000 072
我希望它适用于像这样的非常小的数字:4.89686e-07 但也不会像 150.22
有什么想法吗? 最好的,
所以,有很多方法可以解决这个问题。我会做的是:
def format_small(x, sep_loc=3):
# check if number is not really small (no 'e' in string representation)
if "e" not in str(x):
# return the string representation
return str(x)
# get the number of decimals
dec = int(str(x).split("-")[1])-1
# for really small numbers add a space at the position indicated by sep_loc
s = format(x, f".{dec+sep_loc-1}f")
return s[:-sep_loc] + ' ' + s[-sep_loc:]
print(format_small(7.2e-05)) # prints 0.000 072
print(format_small(150.21)) # prints 150.21
print(format_small(0.12)) # prints 0.12
print(format_small(4.89686e-07)) # prints 0.00000 049
我认为 format
语言中没有任何内容可以满足此要求,但您可以轻松编写自己的辅助函数。
def format_with_space(number, decimals=6):
as_str = f'{{:.{decimals}f}}'.format(number)
chunks = []
start_chunk = as_str.find('.') + 4
chunks.append(as_str[:start_chunk])
for i in range(start_chunk, len(as_str), 3):
chunks.append(as_str[i:i+3])
return ' '.join(chunks)
print(format_with_space(7.2e-05)) # 0.000 072
print(format_with_space(150.22, decimals=3)) # 150.220
print(format_with_space(7.2e-05, decimals=20)) # 0.000 072 000 000 000 000 00