首页 > 解决方案 > 如何用python格式化非常小的数字?

问题描述

我正在查看加密货币的价格。当转换成比特币或有时甚至是美元时,我从我使用的 api 中得到非常少的金额。

这是我能得到的响应类型:

这是我所做的:

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 这样“打破”更高的数字

有任何想法吗?最好的,

标签: pythonfloating-pointformat

解决方案


I don't think there is anything in the format language to accommodate this but you can easily write your own helper function.

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

推荐阅读