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?
2
Answers
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.:
Output:
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 thestr()
function in Python can achieve this.