如何在python中的类中设置浮点格式?

Imo*_*mog 5 python string floating-point formatting class

我想将放在其中的数字格式化为浮点数,定点数到小数点后两位或三位。但是我的代码不起作用

class Quake:
    """Earthquake in terms of latitude, longitude, depth and magnitude"""

    def __init__(self, lat, lon, depth, mag):
        self.lat=lat
        self.lon=lon
        self.depth=depth
        self.mag=mag

    def __str__(self):
        return "M{2.2f}, {3.2f} km, lat {3.3f}\N{DEGREE\
         SIGN lon {3.3f}\N{DEGREE SIGN}".format(
            self.mag, self.depth, self.lat, self.lon)
Run Code Online (Sandbox Code Playgroud)

这将产生错误消息:

'AttributeError: 'float' object has no attribute '2f''
Run Code Online (Sandbox Code Playgroud)

tia*_*ago 3

您需要对格式代码进行编号。另外,如果您确实想{在使用新格式代码时进行打印,则必须使用 double{{来转义格式:

"M{0:2.2f}, {1:3.2f} km, lat {2:3.3f}N{{DEGREE SIGN}} lon {3:3.3f}\N{{DEGREE SIGN}}".format(
self.mag, self.depth, self.lat, self.lon)
Run Code Online (Sandbox Code Playgroud)

  • OP 错过了`:`。没有必要对它们进行“编号”。`{:2.2f}` 从 Python 2.7 开始工作。 (7认同)