Reputation: 3157
I'm wondering if it have a way to do what I want.
Using format
string built-in method, it's possible to print a float as an int :
some_float = 1234.5678
print '%02d' % some_float # 1234
It's also possible to do that by extending the class 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"
I want to print an int as a float :
some_int = 12345678
print '{WHAT?}'.format(some_int) # I want 1234.5678
print '{WHAT ELSE?}'.format(some_int) # I want 123456.78
Do you have any idea to how to do this ?
Using format
or anything else but keep in mind that I do not know in advance the number of decimal digits
Upvotes: 3
Views: 2225
Reputation: 42778
You can divide your number by 10000 or 100:
some_int = 12345678
print '{0:.4f}'.format(some_int / 10000.0)
print '{0:.2f}'.format(some_int / 100.0)
or with a variable amount of decimals:
decimals = 3
print '{0:.{1}f}'.format(some_int / 10.0**decimals, decimals)
Upvotes: 6