我想将放入其中的数字格式化为 float ,定点数保留两位或三位小数。但是我的代码不起作用
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)
这会产生错误信息:
'AttributeError: 'float' object has no attribute '2f''
最佳答案
您需要对格式代码进行编号。另外,如果你真的想在使用新格式代码时打印 {
,你必须使用双 {{
来转义格式:
"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)
关于python - 如何在 python 的类中格式化 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16223767/