E notation in textboxes with data binding

Hi,

I have textbox with a databinding. When I populate the textbox with the databinding from self.item with a decimal number 0.00005 the textbox changes the notation to 5e-05.

How can I change this behaviour so that it always shows the decimal number?

Here is a clone app replicating the behavior:

So this was a fun learning experience:

The issue is that at a certain point in python when float numbers are small enough or big enough, it automatically converts them to scientific notation. So far as I can tell from my research, you have to manually mangle the float as a string with formatting to have it look correctly:

I did this by adding an event handler when data bindings refresh to format any floats that include positive or negative scientific notation.


    def from_scientific_notation(self, number):
        number = float(number)
        num_str = str(number)
        if number < 1 and "e" in num_str:
            decimal_number = int(num_str.split("e")[-1]) * -1
            number = f"{number:.{decimal_number}f}"
            

        if not isinstance(number, str) and number >= 1:
            number = int(number)

        return number

    def form_refreshing_data_bindings(self, **event_args):
        """This method is called when refresh_data_bindings is called"""
        self.item["textbox_number"] = self.from_scientific_notation(self.item["textbox_number"])

I just did this on the clone line 8:
self.item = dict(textbox_number="{:f}".format(0.00005).rstrip('0'))

image

(Default for {:f} will only work down to 0.000001 though…)

Thanks for your answers. I thought that I could solve this easily by using decimal — Decimal fixed point and floating point arithmetic — Python 3.12.4 documentation but it is not yet implemented in Skulpt

1 Like

Even if decimals were available in Skulpt, using them to solve a formatting problem would be the wrong approach.

See this post (and the whole thread) for more details: Stange rounding of numbers in Confirmation - #8 by stefano.menci

2 Likes