我想知道它是否有办法做我想做的事。
使用 format
string 内置方法,可以将 float 打印为 int :
some_float = 1234.5678
print '%02d' % some_float # 1234
也可以通过扩展类 string.Formatter 来做到这一点:
class MyFormatter(Formatter):
def format_field(self, value, format_spec):
if format_spec == 't': # Truncate and render as int
return str(int(value))
return super(MyFormatter, self).format_field(value, format_spec)
MyFormatter().format("{0}{1:t}", "", 1234.567) # returns "1234"
我想做什么
我想将 int 打印为 float :
some_int = 12345678
print '{WHAT?}'.format(some_int) # I want 1234.5678
print '{WHAT ELSE?}'.format(some_int) # I want 123456.78
你知道怎么做吗?
使用 format
或其他任何方式,但请记住我事先不知道小数位数
最佳答案
您可以将您的数字除以 10000 或 100:
some_int = 12345678
print '{0:.4f}'.format(some_int / 10000.0)
print '{0:.2f}'.format(some_int / 100.0)
或可变数量的小数:
decimals = 3
print '{0:.{1}f}'.format(some_int / 10.0**decimals, decimals)
关于python - format() int 为 float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33854486/