How to Remove Decimal in Python

How to Remove Decimal in Python

We have worked with different kind of numbers in Python and modified their type as per our need.

In this tutorial, we will discuss how we can remove decimal in Python.

Let’s start with a simple program,

Output:

<class 'int'>
<class 'float'>
<class 'complex'>

Explanation:

In the above program, we have declared a,b and c as 24, 19.4, and 3+4j respectively.

On checking their type, we came to know a belongs to class ‘int’, b belongs to class ‘float’ and c belongs to class ‘complex’.

Here we have to work on the float numbers, so let’s list out the different methods of removing decimals from numbers.

  1. Using trunc() function
  2. Using int()
  3. Using split()

Let’s discuss each one of them in detail-

Using trunc() Function

In the first program, we will make use of trunc() function and remove the decimal present in the numbers.

The following program illustrates the same-

Output:

523
<class 'int'>
21
<class 'int'>
182
<class 'int'>
211
<class 'int'>
19
<class 'int'>

Explanation:

Let’s have a look at the explanation of the above program-

  1. Since we have to use the trunc() function, we have imported the math module.
  2. We have provided five different decimal values to five variables and checked their type after they are passed in the trunc() function.
  3. On executing the program, it displays the required output.

Using int()

It’s time to know the second approach which is removing decimal using int().

The program given below shows how it can be done-

Output:

<class 'float'>
<class 'float'>
<class 'float'>
523
21
182
<class 'int'>

Explanation:

Let’s understand what we have done here-

  1. In the first step, we have provided float values to three variables and checked their type.
  2. After this, we have passed each variable to int() and stored them to a new variable.
  3. Finally, we have printed the values stored in these variables.
  4. On executing this program, the expected output is displayed.

Using split()

Finally, in the last approach, we will use the interesting split() to obtain the integer values.

The following program illustrates the same-

Output:

The resultant list is: [523, 21, 182, 211, 19]

Explanation:

Let’s have a look at the explanation of the above program-

  1. In the first step, we have created a list that contains all the decimal values.
  2. After this, we have declared an empty list and appended the values in it.
  3. In the next step, we have taken each element from that list and passed it into an int().
  4. Finally, we have displayed the resultant list that contains the numbers without decimal.

Conclusion

In this Tutorial, we started with a general idea of the type of numbers we use in Python and then learned the various methods of removing decimals from the numbers.


原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263384.html

(0)
上一篇 2022年5月30日
下一篇 2022年5月30日

相关推荐

发表回复

登录后才能评论