reflex icon indicating copy to clipboard operation
reflex copied to clipboard

rx.text component does not support formatting floats

Open pedrojfernandez opened this issue 2 years ago β€’ 10 comments

I'm trying to format a float as a currency (euros) and I'm using f string for that:

rx.text (f"{AppState.total:.2f}€")

but when the string is generated, if the number has any right decimal equal to zero, they don't appear. For example: float 6, I want to get "6.00€", but I get "6€". Any idea? In a empty python script it works, but not inside this "framework". May be something is happening in between in the rx.text component generating the output.

pedrojfernandez avatar Nov 08 '23 19:11 pedrojfernandez

Hey team reflex, this seems like a good first issue. Would love to take this up!

cloud-shannon avatar Nov 10 '23 08:11 cloud-shannon

@etaldot sounds good! Just assigned you to it

picklelo avatar Nov 10 '23 19:11 picklelo

I think for this you have to modify the Var.__format__ method here: https://github.com/reflex-dev/reflex/blob/ce47fcfd6cf0f2886c95363b6b84fe3950d07b4e/reflex/vars.py#L279

We will have to read the format_spec and compile it out to the equivalent JS code to format the number

picklelo avatar Nov 14 '23 22:11 picklelo

Hi @picklelo thanks for the directions. I will put up a PR today.

cloud-shannon avatar Nov 15 '23 07:11 cloud-shannon

Still doesn't work?

kairess avatar Feb 28 '24 09:02 kairess

@picklelo @socalledso Any updates on this bug? Seems to still be present in 0.4.9.

tlifke01 avatar Jun 07 '24 16:06 tlifke01

Up

curlup avatar Aug 27 '24 15:08 curlup

This requires overriding the Var format function for NumberVar to be aware of the format_spec and adjust itself if needed. The issue is that it's quite difficult to cover all of Python's format behavior with JS functions.

Not sure if we're going to get to it, but as a workaround, you can define a computed var that is the result of that expression, for example:

class AppState(rx.State):
    total: int = 6.0

    @rx.var
    def total_formatted(self) -> str:
        return f"{self.total:.2f}€"

def index():
    return rx.text(AppState.total_formatted)

adhami3310 avatar Sep 26 '24 21:09 adhami3310

@adhami3310 where's the source code for someone to start thinking about implementing Var format function for NumberVar to be aware of the format_spec ? Thanks

curlup avatar Oct 02 '24 18:10 curlup

where's the source code

That would generally be in reflex/vars, you would need to define __format__ in NumberVar in reflex/vars/number.py and add special case handling for format_spec is provided.

adhami3310 avatar Oct 02 '24 18:10 adhami3310

How does one figure out which version this is simplemented in?

curlup avatar May 21 '25 02:05 curlup

@curlup you check the release notes, it's been there since 0.7.2

adhami3310 avatar May 21 '25 02:05 adhami3310