Python format float as int

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.

Asclepius

51.8k15 gold badges149 silver badges131 bronze badges

asked Nov 22, 2012 at 11:19

6

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.

answered Mar 7, 2019 at 19:21

jxramosjxramos

6,3826 gold badges49 silver badges92 bronze badges

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"

answered Nov 22, 2012 at 13:49

berealbereal

30.2k6 gold badges53 silver badges93 bronze badges

0

This works:

from math import trunc
some_float = 1234.5678

print '{:d}'.format[trunc[some_float]]
=> 1234

Or just do this, for that matter:

print trunc[some_float]
=> 1234

I think it's an acceptable answer, it avoids the conversion to int. Notice that in this snippet: '%02d' % some_float an implicit conversion to int is happening, you can't avoid some sort of conversion for printing in the desired format.

answered Nov 22, 2012 at 11:25

Óscar LópezÓscar López

227k35 gold badges302 silver badges376 bronze badges

This will work too:

some_float = 1234.5678
f = lambda x: str[x][:str[x].find['.']]
print '{}'.format[f[some_float]]
=> 1234

After doing a %timeit test it looks like this is a bit faster than the trunc method.

answered Dec 3, 2015 at 8:35

5

Not the answer you're looking for? Browse other questions tagged python format or ask your own question.

Converting a float value to an int is done by Type conversion, which is an explicit method of converting an operand to a specific type. However, it is to be noted that such type of conversion may tend to be a lossy one [loss of data]. Converting an int value like 2 to floating-point will result in 2.0, such types of conversion are safe as there would be no loss of data, but converting 3.4 to an int value will result in 3 leading to a lossy conversion. 
Examples: 

Input:  3.3 
Output: 3 

Input:  5.99
Output: 5

Method 1: Conversion using int[]:

To convert a float value to int we make use of the built-in int[] function, this function trims the values after the decimal point and returns only the integer/whole number part.

Syntax: int[x] 

Return: integer value

Example 1: Number of type float is converted to a result of type int.

Python3

num = 9.3

print['type:',

      type[num].__name__] 

num = int[num]  

print['converted value:', num,

      ', type:', type[num].__name__]

Output

type: float
converted value: 9 , type: int

Example 2: In most cases the int[] function rounds off the result to an integer lesser than or equal to the input, but the behavior is neither definite nor predictable. One such example is shown below.

Python3

num1 = 5.9

num2 = 5.99999999999999999999

num1 = int[num1]

num2 = int[num2]

print[num1, num2, sep = '\n']

Method 2: Conversion using math.floor[] and math.ceil[].

A float value can be converted to an int value no larger than the input by using the math.floor[] function, whereas it can also be converted to an int value which is the smallest integer greater than the input using math.ceil[] function. The math module is to be imported in order to use these methods.

Syntax: math.floor[x]

Parameter:

x: This is a numeric expression.

Returns: largest integer not greater than x.

Syntax: math.ceil[x]

Parameter:

x: This is a numeric expression.

Returns: Smallest integer not less than x.

Example : In the below example conversion from float to int has been achieved using the floor[] and ceil[] methods, the former returns an int no larger than the input and the latter returns the smallest integer larger than the input.

Python3

import math      

num = 5.6

floor_value = math.floor[num]

ceil_value  = math.ceil[num]

print["the result using floor[] : ",

      floor_value ,

      ', type : ',type[floor_value].__name__]

print["the result using ceil[]  : ",

      ceil_value,

      ', type: ', type[ceil_value].__name__]

Output

the result using floor[] :  5 , type :  int
the result using ceil[]  :  6 , type:  int

Method#3: Conversion using round[ ].

A float value can be converted to an int value which is closet integer value if does not pass second parameter. In case of equal difference it goes toward larger integer.

Syntax: round[x]

Parameter:

x: This is a numeric expression.

Returns: integer multiple of closest.

Example : In the below example conversion from float to int has been achieved using the round[] methods, the former returns an int number which is closest to number.

Python3

num = 5.6

print[ 'Type : ', type[num].__name__]

print[ "Original number is : ", num]

value = round[num]

print[ 'Type : ',type[value].__name__]

print["the result using round  : ",value]

Output

Type :  float
Original number is :  5.6
Type :  int
the result using round  :  6

Method#4: Conversion using math.trunc[ ].

A float value can be converted to an int value. In case of negative number it behaves like ceiling function of math library and in case of positive number it behaves like floor function..

Syntax: math.trunc[x]

Parameter:

x: This is a numeric expression.

Returns: larger integer in case of negative number else in case of positive number smaller number.

Example : In the below example conversion from float to int has been achieved using the math.trunc[] methods, the former returns an larger int number which in case of negative number, else in case of positive number return smaller integer number.

Python3

import math

num = 5.6

num2 = -2.6

value = math.trunc[num2]

print[ 'Type of value : ',type[value].__name__]

print["the result using round  : ",value]

data = math.trunc[num]

print[ 'Type of data: ',type[data].__name__]

print["the result using round  : ",data]

Output

Type of value :  int
the result using round  :  -2
Type of data:  int
the result using round  :  5


Can you change 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.

How do I convert float to int?

Since a float is bigger than int, you can convert a float to an int by simply down-casting it e.g. [int] 4.0f will give you integer 4. By the way, you must remember that typecasting just get rid of anything after the decimal point, they don't perform any rounding or flooring operation on the value.

How do I format a float number in Python?

Format float value using the round[] Method in Python The round[] is a built-in Python method that returns the floating-point number rounded off to the given digits after the decimal point. You can use the round[] method to format the float value.

What is %s %d %F in Python?

Answer. In Python, string formatters are essentially placeholders that let us pass in different values into some formatted string. The %d formatter is used to input decimal values, or whole numbers. If you provide a float value, it will convert it to a whole number, by truncating the values after the decimal point.

Chủ Đề