How to truncate numbers to integers in Python

Hello there, my dear fellow python programmers. Today we are going to talk about how to truncate numbers to integers in Python.

Let’s start by talking about what is truncation itself.

 

Truncation of Number:

Well, truncation could be simply understood as removing everything beyond the decimal point and leaving just the integer part of the number.

Truncation could be helpful in fields like data science where we want to reduce the randomness of data because we look for generalization.

Moreover, longer formats cause storage as well as computational cost.

Now, let us talk about how we do this:

 

Ways to Truncate Numbers:

There are primarily two ways:

  1. Using the math.trunc function.
  2. Using the built-in int() function.

Now, let us see how we make use of these.

 

Using the math.trunc function:

The trunc() function is a built-in function under the math library in python.

It truncates the fractional part or the part after the decimal in a number towards zero.

That is it removes whatever follows the decimal point in a number.

Lets us see how that happens with the help of some code:

import math

#Some random numbers
A = 13.4573454
B = 2.56457544
C = 0.123544
D = 57.3435534

# Truncation using trunc() function
truncated_A = math.trunc(A)
truncated_B = math.trunc(B)
truncated_C = math.trunc(C)
truncated_D = math.trunc(D)

# Output:
print(A, "truncated =", truncated_A)
print(B, "truncated =", truncated_B)
print(C, "truncated =", truncated_C)
print(D, "truncated =", truncated_D)

Here, we have imported “math” library, because trunc() function comes under the math library in python.

 

Now let us look at the output of the following:

OUTPUT:

truncate numbers to integers

 

Yaa, that worked like anything.

Now, let’s move on and see another method using int().

 

Using the int() function:

Well, the int() function is a built-in function in python.

It takes in numbers and strings and returns an integer value.

This function can be used to truncate integers.

Let us see how with the help of a code:

 

#Some random numbers
A = 13.4573454
B = 2.56457544
C = 0.123544
D = 57.3435534

# Truncation using trunc() function
truncated_A = int(A)
truncated_B = int(B)
truncated_C = int(C)
truncated_D = int(D)

# Output:
print(A, "truncated =", truncated_A)
print(B, "truncated =", truncated_B)
print(C, "truncated =", truncated_C)
print(D, "truncated =", truncated_D)

Now, let us have a look at how this comes out to be:

OUTPUT:

truncate numbers to integers

 

And there you have it, “How to truncate numbers to integers in Python”.

Hope you enjoyed the read.

Thanx for reading.

 

Leave a Reply

Your email address will not be published. Required fields are marked *