Format truncated Python float as int in string

format, python

Solution

It's possible to extend the standard string formatting language 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}", "Hello", 4.567)  # returns "Hello 4"

Problem

A quick no-brainer: ``` some_float = 1234.5678 print '%02d' % some_float # 1234 some_float = 1234.5678 print '{WHAT?}'.format(some_float) # I want 1234 here too ``` Note: `{:.0f}` is not an option, because it rounds (returns `1235` in this example). `format(..., int(some_float))` is exactly the thing I'm trying to avoid, please don't suggest that.

Original source