skip to Main Content

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


  1. 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
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search