slint-ui / slint

Slint is a declarative GUI toolkit to build native user interfaces for Rust, C++, or JavaScript apps.
https://slint.dev
Other
17.67k stars 611 forks source link

Float-to-string conversion while controlling decimal place count #5822

Open Enyium opened 3 months ago

Enyium commented 3 months ago

It's a basic UI necessity to display floats in a controlled format. Currently, you can only let your float be displayed with inappropriate accuracy (like 5.9993034 in stead of 6.0) or implement it yourself. Trying to round yourself in the float domain, then accepting implicit conversion to string can lead to base-2-related problems like 3.299999999999 or omission of an intended .0 suffix. Slint should provide such functionality. It could copy JavaScript's toFixed() and maybe also toPrecision(), which return strings.

Ideally, Slint would be aware of the current locale (from the translation context?) and use the appropriate decimal separator - also with regular auto-conversions.

ogoffart commented 3 months ago

Thanks for filing an issue.

As a workaround, toPrecision can be emulated with something like round(foo * 100) / 100 but it's just a workaround. As another workaround, it is possible to implement in native code in a global callback.

ogoffart commented 3 months ago

Added as good first issue now that the number.sqrt() and similar are merged, it can just be done similarly.

What needs to be done is:

marcothaller commented 3 months ago

I was also looking for a convenient solution to convert floats to a string on the UI with a fixed number of decimals and potentially a minimum width.

I looked into the slint code Olivier pointed to and attempted to implement a solution utilizing std::fmt. std::fmt's concept of precision is this:

For floating-point types, this indicates how many digits after the decimal point should be printed.

So specifying the digits to appear after the decimal points (like with toFixed()) can easily be done with std::fmt but specifying the number of significant digits (like with toPrecision()) is not supported out-of-the-box with std::fmt IMO.

My main interest was in providing a proposal for setting the number of digits after the decimal point and for setting the width. The code can be found here

ogoffart commented 3 months ago

@marcothaller Thanks. I added a few comment to the commit.

On a unrelated note, i wonder if the function should follow the locale or not.