简体   繁体   English

格式化浮点数的十进制数字? - PYTHON

[英]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.例如,有一个名为“yaw”的浮点值,它会根据无人机的运动不断变化。 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.他们限制了数字 121.5232 但每当这个值的最后一个数字变为 0 时,最后一个数字就会消失,看起来像:121.542,我想解决这个问题。 Why it is not giving me 121.5420??.为什么它不给我 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.如果您能提供帮助,我将不胜感激。

You can use:您可以使用:

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

or if you are using Python 3.6+ you can use f-strings或者如果您使用的是 Python 3.6+,您可以使用f-strings

f"{yaw:.4f}"

Some examples:一些例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM