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.
It's possible to extend the standard string formatting language by extending the class string.Formatter:
It's worth mentioning the built in behavior for how floats are rendered using the raw format strings. If you know in advance where your fractional part lies with respect to 0.5 you can leverage the format string you originally attempted but discovered it fell short from rounding side effects
"{:0.0f}"
. Check out the following examples...As you can see there's rounding behavior behind the scenes. In my case where I had a database converting ints to floats I knew I was dealing with a non fractional part in advance and only wanted to render in an html template the int portion of the float as a workaround. Of course if you don't know in advance the fractional part you would need to carry out a truncation operation of some sort first on the float.
This will work too:
After doing a %timeit test it looks like the trunc function from math library is faster, so
math.trunc
would be preferred if you need to format many numbers this way.This works:
Or just do this, for that matter:
I think it's an acceptable answer, it avoids the conversion to
int
. Notice that in this snippet:'%02d' % some_float
an implicit conversion toint
is happening, you can't avoid some sort of conversion for printing in the desired format.