Как преобразовать float в int
Перейти к содержимому

Как преобразовать float в int

  • автор:

Python Program to Convert Float to Int

Python Program to Convert Float to Int

Irrespective of what language you are programming in, data types play a major part in your program. There are various types of programming language to deal with and hence, there are times when you get stuck to converting them into one form to another. In this article, let us study how you can convert float data type to int data type in python using various external methods and their respective outputs. But before jumping to type conversions, let us have a flashback to the introduction of float and integer data types.

What is Integer in Python?

Integer in python can be treated as the whole number which can be either positive or negative. As an integer is considered to be the whole number, it does not consist of any decimal points and hence can extend up to the computer’s limit. Int is by default decimal, i.e., base 10 although you can later convert it from one form to another. Let us understand int data type better with the example below:

For example:

Output:

What is Float in Python?

Well, the float-point data type is no more different than an integer in python. Unlike integer data types, float-point consist of any number with a decimal point. According to IEEE 754 standards, the float-point data type is a 64-bit double-precision number. You can generally define them with the binary fractions(base-2) and later convert them to any other form using type conversion.

For example:

Output:

How to Convert Float to Int in Python?

Below are some of the methods by which you can convert float to int in python.

1) Using int() method

Python provides multiple in-built methods which help you to ease your programming. Int() is one such method used to convert any data type into an integer with minimal steps. The function takes the float-point variable as the argument and trims the values after the decimal points. As the result, the final output will be the integer or whole number. Let’s understand the working of the int() method with the example below:

For example:

Output:

Remember that in most cases, the int() function rounds off the results to the integer lesser than the decimal point. However, sometimes there’s an exception hence we cannot predict or define the behavior for the same.

For example:

Output:

2) Using math.floor() and math.ceil()

If you have already decided to convert float value to an int value no larger than the input, make use of the floor() method and pass the value as the parameter to the method. Whereas, if you wish to convert it to a value greater than the original, make use of the ceil() method as shown in the example below:

For example:

Output:

Note that floor() and ceil() methods are the part of math() library and therefore, you need to import the math library before using it.

3) Using trunc() method

Python provides the in-built function i.e., trunc() method which helps to provide the integer value. Here, the method takes the float-point value as the parameter and ignores everything after the decimal point. Let us understand the use of trunc() method in the example below:

For example:

Output:

4) Using numpy library

Till now, you studied how to convert a single floating-point to an integer value. But what if you are provided with the collection of multiple float values and need to get the corresponding integer values from it. In this case, you have to import the NumPy library and make use of the astype() method. Doing this will provide you with the integer value as shown in the below example:

For example:

Output:

Limitations for Converting Float to Int in Python

  • Although you use the int() method for type conversions it is not recommended to use as there could be the chances of data loss.
  • You can make use of the math module to avoid the loss of data. However, the situation of data loss does not change if the function is not used wisely.

Conclusion

Type conversion plays an important role while programming your code irrespective of the language you use. In this article, we studied how you can convert float to int in python using various explicit methods and their corresponding example. It is recommended to get good command on these conversions for better and more efficient programming practice. To learn more about such type conversions in python, visit our blogs at favtutor.

Sidebar

RSS Latest

Converting float to int in C

In this post, we’ll see how to convert a float to an int in C. We’ll assume both int and float datatypes to be 32-bits long an int using two’s complement representation for negative values. The conversion will be performed using the bit-level representation of the float data type. Only addition, subtraction, and bitwise operations will be used.

To convert from int to float , you can see this post.

This is also a solution for exercise 2.96 of the Computer Systems: A Programmer’s Perspective book.

Rounding to whole numbers

Before we begin, let’s study how C will handle rounding from float to int . The rounding mode used is round towards zero.

For positive values, we round down:

Negative values are rounded up:

In practical terms, the fractionary part is truncated.

Getting the floating-point fields

The floating-point single-precision data representation ( float ), consists of three different fields.

source

These fields are used to encode a number in the form:

  • One bit encodes the sign: s .
  • 8 bits encode the exponent, E. We’ll call this bits exp (in green on the image above).
  • 23 bits encode the magnificand, M. We’ll call them frac bits (in red on the image above).

For our converter, we’ll start by getting these different fields.

They are obtained by shifting operations combined with masks to get the necessary bits. On the code snippet above, f contains the 32-bit float representation of the value.

Special cases: NaN and Infinity

Floating-point encodes special values such as NaN (not a number, obtained by expressions such as sqrt(-1) or 0.0 / 0.0 ) and infinity (for values that overflow) with the exp field all set to ones. For these special cases, we’ll return the special value 0x80000000 (which corresponds to INT_MIN ).

A value preceded by 0x , such as 0xFF , is used to denote an hexadecimal number.

Denormalized values

Denormalized values are those in which the exp field is all zeros. In floating-point representation, they are used to encode values that are very close to zero (both positive and negative). All of these values will be rounded to zero.

Normalized values

Finally, we can focus on normalized values. In this case, the exp field is neither all ones nor all zeros. For this group of values, the exponent E is encoded as:

Where exp is the unsigned 8-bit number represented by the exp field and Bias = 127. We can get the exponent E as follows:

Values less than one

First, let’s consider values that are in the range -1 to 1 (not including -1 and 1). All of these values will be rounded to zero. Positive values will be rounded down, and negative values will be rounded up. In both cases, the result will be 0. These cases will take place when the exponent E is less than 0:

For instance, if E = -1 , the encoded float will be a binary fraction in the form:

Where XXX represents the fractionary part of the magnificand, encoded by the frac field. 0.1XXX is a binary fraction less than one.

Overflowing

The range of int values is between INT_MIN = -2^31 = 2147483648 and INT_MAX = 2^31 — 1 = 2147483647 . For float values beyond that range, we’ll return 0x80000000 as a way of encoding overflow.

The int datatype represents numbers using 31 bits (the remaining bit is used for the sign). This means that the binary representation of our value can be at most 31 bits long. This limit case will take place when E = 30 :

X. X are the 23 bits of the frac field. The value 1X. X0. 0 will be 31 bits long: a leading one + 23 frac bits + 7 zeros.

We can conclude that float will overflow when E > 30 :

Normalized values in the range of int

Finally, we’re left with the float values that can be rounded to an int other than zero and that won’t overflow.

The frac field is 23 bits long. Remember that the exponent E and frac encode a value in the form:

Where each X is one of the 23 binary digits of the frac field. They represent the digits that come after the binary point (fractionary part).

A positive value of E will shift the binary point E places to the right. For instance if E = 2 :

Here we’re using the symbol Y for the 21 frac binary digits that come after the binary point.

As it was mentioned above, when we cast a float to int , C will truncate the fractionary part.

That means that the rightmost 23 — 2 = 21 bits of the frac field are discarded.

On the other hand, if E is larger than 23, the binary point will be shifted beyond the bits of the frac field and we’ll have extra zeros to the right:

We will have E — 23 trailing zeros.

These conditions can be fulfilled by the appropriate shifting operations. We shift frac to the right ( >> ) in order to discard the least significant bits when E < 23 , and we shift to the left ( << ) to add trailing zeros.

Here x is the resulting bit-level int representation. First, we shift the leading one E places to the left. Then, we get the integer part of the float value by shifting operations as it was mentioned above. Note that we use the bitwise OR operator ( | ) as a way of “adding” the leading one and the lower order bits of the frac field (e.g. 100 | 001 = 101 ).

Negative values

Finally, we modify the bit encoding for negative values.

x+1 is just a binary operation that yields -x in two’s complement representation.

Complete program and testing

Putting all of the pieces together in the float_f2i function, we get:

In order to handle the bit-level representation of float values with bitwise operators, we use the unsigned datatype which we call float_bits . Additionally, we wrote some of the numerical constants as K = 8 for the length of the exp field and N = 23 for the length of the exp field.

Testing

The program was tested as follows:

We used the variable bits to generate all the possible bit-level combinations. The address of bits was then referenced as datatypes float and float_bits to perform the test. Finally, we verified that the result of casting float to int was the same as the return value of the float_f2i function.

When compiled, we received no error output which means that the converter worked for all of the tested values.

Преобразование типов: с float в int в Java

Преобразование типов данных – это распространенная практика в программировании на Java. Однако, преобразование с плавающей точкой (float) в целочисленный тип (int) может вызвать некоторые сложности из-за того, что тип float может содержать дробные числа, в то время как тип int – только целые.

Предположим, есть число с плавающей точкой 8.61f, и его нужно преобразовать в целое число. Простое приведение типа, как показано ниже, даст результат 8, что может не соответствовать ожиданиям.

Аналогичная ситуация происходит с отрицательными числами. Если есть число -7.65f и его нужно преобразовать в целое число, то приведение типа даст результат -7.

Проблема в том, что при приведении типа float к типу int, дробная часть числа просто отбрасывается, вне зависимости от того, было ли оно больше или меньше 0.5. В результате, число округляется в меньшую сторону.

Однако, есть способ округлить число до ближайшего целого вместо того, чтобы просто отбрасывать дробную часть. Это может быть сделано с помощью метода Math.round(). Этот метод принимает число с плавающей точкой в качестве аргумента и возвращает ближайшее целое число. Если дробная часть числа больше или равна 0.5, число округляется вверх, иначе — вниз.

В обоих примерах результатом будет 9 и -8 соответственно, что является более точным округлением.

Какую и как использовать функцию, чтобы float сделать int?

Какую функцию нужно использовать, чтобы передать GET запросом строку с кирилическими символами?
чтобы передать GET запросом строку с кирилическами символами какую функцию преобразования кирилицы.

ОШИБКА [Error] cannot convert ‘int*’ to ‘float*’ for argument ‘1’ to ‘void Syma(float*,int*,int)
Какая то проблема с указателями,незнаю,не хочет щитать суму парних чисел в второй.

Какую функцию можно использовать как пробел?
нужно чтобы между данными был пробел, как это осуществить?

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *