Formatting zeros after decimal for floats from a SQL model

I’m trying to format a float as currency, but so far have run into errors with what I would normally use in python. Locale.currency produces a type error and using “:.2f” doesn’t seem to work. I want to have the “Amount” column formatted as “$123.00” or “$12.53”. The State.results is a basic session.query. Any ideas?

Here’s the code.

class Accounts(rx.Model, table=True):
    id: Optional[int] = Field(primary_key=True)
    Name: str
    Number: int
    ID: str
    Amount: float

def show_account(row: Accounts):
    return rx.table.row(
        rx.table.cell(row.Name),
        rx.table.cell(row.Number),
        rx.table.cell(row.ID),
        rx.table.cell(row.Amount),
    )

def index():
    return rx.fragment(
        rx.table.root(
            rx.table.header(
                rx.table.row(
                    rx.table.column_header_cell("Name"),
                    rx.table.column_header_cell("Number"),
                    rx.table.column_header_cell("ID"),
                    rx.table.column_header_cell("Amount"),
                )
            ),
            rx.table.body(
                rx.foreach(State.results, show_account),
            ),
        ),
    )

There are different ways of achieving this. One way is to define a custom var operation:

from reflex.vars import NumberVar, var_operation, var_operation_return


@var_operation
def two_decimal_points(value: NumberVar):
    """This function will return the value with two decimal points."""
    return var_operation_return(
        js_expression=f"({value}.toFixed(2))",
        var_type=str,
    )

and use it as:

rx.table.cell(two_decimal_points(row.Amount))

This works. Thanks @khaleel
How would I also add the comma to finish formatting it as money for amounts in the thousands or tens of thousands? I.E. 10,000.00 instead of 10000.00

With the help of ChatGPT, i asked:

given a number in js, how to convert it to a string with two fixed digits after the dot and a comma between groups of three digits, prefer native api over string manipulation

the given solution, adopted to reflex syntax, would be:

from reflex.vars import NumberVar, var_operation, var_operation_return


@var_operation
def two_decimal_points(value: NumberVar):
    """This function will return the value with two decimal points."""
    return var_operation_return(
        js_expression=f"(new Intl.NumberFormat('en-US', {{minimumFractionDigits: 2, maximumFractionDigits: 2}}).format({value}))",
        var_type=str,
    )