. Advertisement .
..3..
. Advertisement .
..4..
Truncating a float in Python is one of the great ways to make the calculating process easier and quicker. You can truncate floats by rounding the number or removing the unnecessary digits.
The following post will offer different available methods to do this task.
How To Truncate A Float In Python
A float is one Python number type, which is used to store a floating-point number and any number with a decimal point. Here are some methods to truncate these floats:
Method 1: Use f-strings
String offers a medium for customization loads on Python variables. You can choose among these customizations manually. To truncate floats, the % sign should be used as the interpolation operator.
As the f-strings
deal with strings, you need to convert the floating-point number to a string as well. Then, navigate to the f"{field_name:[.precision][type]}"
syntax and specify the number at the desired places.
The floats will be truncated into these places in the precision space. Now, it’s time to use the float()
function to use the corresponding function above as an argument
Code:
x = 1.256998
txt = f"{x:.2f}"
y = float(txt)
print(y)
Output:
1.26
Method 2: Use The int() Function
The int()
function can also be employed to truncate floats in Python. Yet, the process is complicated as follows:
First, multiply the float by 10**x. In this case, x is the digit number after the decimal. This way, you can drop the excess characters from the floating-point number. Then, divide the number with the same 10** value and convert it back to float.
Code:
def trunc(a, x):
int1 = int(a * (10**x))/(10**x)
return float(int1)
print(trunc(1.256998,2))
Output:
1.25
Method 3: Use The str() Function
To use this method, you need to convert the float to a string first. After that, all you need to do is search for the resultant string’s decimal point. If there exists a decimal point, let’s specify the saved digits after this decimal.
In this case, use the try…catch statement to remove the unnecessary places.
Code:
def trunc(a,x):
temp = str(a)
for i in range(len(temp)):
if temp[i] == '.':
try:
return float(temp[:i+x+1])
except:
return float(temp)
return float(temp)
print(trunc(1.256998,2))
Output:
1.25
Method 4: Use The round() Function
The predefined round()
function can round off all floating-point numbers. There are two parameters for the number to be operated on.
Unlike other methods, this one rounds off and truncates the floating-point number at the same time.
Code:
print(round(1.256998,2))
Output:
1.26
Conclusion
This above tutorial explains four useful approaches to truncate a float in Python. Truncating the floating-point numbers will make the calculations much simpler. So if you want to make your output values more reader-friendly, let’s try these above truncating methods.
Leave a comment