python - 如何用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 这样“打破”更高的数字
有任何想法吗?最好的,
解决方案
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
推荐阅读
- yarnpkg - 如何从 Yarn2 降级到 Yarn1?
- java - 将预期异常传递给 assertThrows:JUnit 5
- javascript - 获取数据(全球?)和导航的存储设计
- javascript - Vue.js中子组件中迭代槽的迭代槽内容
- azure-functions - 多功能应用程序未部署
- django - 十进制字段无法更新值
- keras - 混淆矩阵值错误:找到样本数量不一致的输入变量:[3, 360]
- c - 当我包含 Esp32 Google Cloud IoT 库函数时 CO2 传感器值发生变化
- javascript - JavaScript 代码未在函数内执行
- javascript - 为什么对象被视为数组?