英文:
How to disable scientific notation for small numbers in FastAPI + Postgres
问题
在我的PostgreSQL数据库中,我有一个包含非常小的数字(例如0.000000022385
)的数值类型列。我有一个FastAPI端点,以以下方式返回这些数据:
@app.get("/data", response_model=List[models.Data_Read], tags=["DataModel"])
async def getall_data():
with Session(database.engine) as session:
query = select(models.data_row)
results = session.exec(query).all()
return results
当我在我的React前端访问这个端点的返回值时,它显示为2.2385e-8
。我想要避免所有这样的情况。我已经尝试在前端处理它,但没有找到任何稳定的方法。相反,我必须对每个这样的值应用一种变通方法。是否有任何方法可以在FastAPI或PostgreSQL中实现这一点?
英文:
In my PostgreSQL database, I have a numeric type column with very small numbers (e.g. 0.000000022385
). I have a FastAPI endpoint which returns this data like so:
@app.get("/data", response_model=List[models.Data_Read], tags=["DataModel"])
async def getall_data():
with Session(database.engine) as session:
query = select(models.data_row)
results = session.exec(query).all()
return results
When I access this endpoint's return value in my React front-end, it shows up like 2.2385e-8
. I want to avoid all such instances. I have tried to do it on the front-end but haven't found any robust method. Instead, I have to apply a workaround to every single such value. Is there any way I can achieve this in FastAPI or PostgreSQL?
答案1
得分: 1
你可以使用 f-strings 来处理这个问题。更具体地说,你可以使用 :.#f
语法。比你指定的数字精度更高的小数将会四舍五入。
例如:
small_num = 0.000000022385
print(f"未格式化: {small_num}")
print(f"格式化: {small_num:.12f}")
more_precise_small_num = 0.000000022385987987897897
print(f"更精确的小数: {more_precise_small_num:.12f}")
输出结果:
未格式化: 2.2385e-08
格式化: 0.000000022385
更精确的小数: 0.000000022386
英文:
You can use f-strings to deal with this. More specifically, you can use the :.#f
syntax. Any decimals more precise than the number you specify will be rounded.
e.g.:
small_num = 0.000000022385
print(f"Unformatted: {small_num}")
print(f"Formatted: {small_num:.12f}")
more_precise_small_num = 0.000000022385987987897897
print(f"more_precise_small_num: {more_precise_small_num:.12f}")
Output:
Unformatted: 2.2385e-08
Formatted: 0.000000022385
more_precise_small_num: 0.000000022386
答案2
得分: 1
这可以通过将数字列转换为字符串表示来实现。
一种方法是修改FastAPI端点以在返回之前更改数值的格式。Python中的format()
或str()
函数可以实现此操作。
英文:
This can be achieved by converting the numeric number column to a string representation.
A way to do this can be to modify the FastAPI endpoint to change the format of the numeric values before returning them. The format()
or the str()
function in Python can achieve this.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论