rx.text component does not support formatting floats
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.
Hey team reflex, this seems like a good first issue. Would love to take this up!
@etaldot sounds good! Just assigned you to it
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
Hi @picklelo thanks for the directions. I will put up a PR today.
Still doesn't work?
@picklelo @socalledso Any updates on this bug? Seems to still be present in 0.4.9.
Up
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 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
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.
How does one figure out which version this is simplemented in?
@curlup you check the release notes, it's been there since 0.7.2