Search code examples
pythondigits

Formatting decimal digits of an float number? --PYTHON


Kind regards friends, I know there are many ways to do it. But all methods I have tried is giving me a conclusion which I don't want. As an example, there is a float value named 'yaw' which constantly changing according to the movement of the drone. I want to limit digits of this yaw value. Whenever I try this methods below:

        self.lbl_yaw.setText("{}".format(str(yaw), ".4f")) # first method
        yaw = round(yaw, 4)                                # second method

they limits the number 121.5232 but whenever last number of this values becomes 0, last number is disappearing and seems like : 121.542 and I want to fix that. Why it is not giving me 121.5420 ??. I'm sure there is a way to do it which I don't know. I would be thankful if you could help.


Solution

  • You can use:

    "{:.4f}".format(yaw)
    

    or if you are using Python 3.6+ you can use f-strings

    f"{yaw:.4f}"
    

    Some examples:

    "{:.4f}".format(4.1234)  # it is '4.1234'
    "{:.4f}".format(4.1230)  # it is '4.1230'