Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format truncated Python float as int in string

Tags:

python

format

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.

like image 957
georg Avatar asked Nov 22 '12 11:11

georg


People also ask

How do I truncate a float to an int in Python?

Use the int Function to Truncate a Float in Python The built-in int() function takes a float and converts it to an integer, thereby truncating a float value by removing its decimal places.

How do you convert float to int in Python?

Python also has a built-in function to convert floats to integers: int() . In this case, 390.8 will be converted to 390 . When converting floats to integers with the int() function, Python cuts off the decimal and remaining numbers of a float to create an integer.


2 Answers

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...

>>> "{:0.0f}".format(1.999) '2' >>> "{:0.0f}".format(1.53) '2' >>> "{:0.0f}".format(1.500) '2' >>> "{:0.0f}".format(1.33) '1' >>> "{:0.0f}".format(0.501) '1' >>> "{:0.0f}".format(0.5) '0' >>> "{:0.0f}".format(0.1) '0' >>> "{:0.0f}".format(0.001) '0' 

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.

like image 73
jxramos Avatar answered Oct 14 '22 02:10

jxramos


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" 
like image 25
bereal Avatar answered Oct 14 '22 00:10

bereal