A Beginner’s Guide to Decimal Points in Python
Skills for controlling decimal values
Handling decimal points is a critical skill in any programming language — especially when the focus is often data science.
Here’s a no-frills guide that covers the basics of rounding, truncating, and formatting decimal points in Python.
Rounding
Just like in elementary school, the first thing we’ll cover is rounding numbers.
To mimic the standard “five and up” rule, we’ll use the standalone round() function.myNum = 3.14159265359print(round(myNum,2) # 3.14
print(round(myNum,4) # 3.1416
What happens if you want to force rounding up or down? There are two methods of the pre-installed math library that can help you out.
To always round up, we’ll use the ceil() method — short for ceiling.from math import ceilmyNum = 3.14159265359print(ceil(myNum)) # 4
To always round down, we’ll use the floor() method — the opposite of a ceiling.from math import floormyNum = 3.14159265359print(floor(myNum)) # 3
Truncating
The next skill in handling decimals is removing decimals, known as truncating. There is no intelligent rounding, simply removing all decimal points.
To do so, we use another method of the math library, named trunc().from math import truncmyNum = 3.14159265359print(trunc(myNum)) # 3
But, what if we want to truncate only some decimals? We’ll need to build a custom function around the trunc() method that specifies how many decimals to keep.from math import truncdef truncate(n,d=0):
if d>0:
return trunc(n * 10**d) / (10**d)
else:
return trunc(n)myNum = 3.14159265359print(truncate(myNum)) # 3
print(truncate(myNum,4)) # 3.1415
Basically, the function moves the decimal d spaces before truncating, then readjusts the decimal before being returned. We define a default value for d so that our function will work just like the normal trunc() method if a second argument is not passed.
Printing Decimals
We move to our third skill, printing decimals.
Now, if you’ve used any of the above techniques to format your decimal value exactly as you’d like then this is easy. We simply use an f-string and place the variable in curly braces.myNum = 3.14159265359myNum = round(myNum,2)print(f"My number is {myNum}") # My number is 3.14
However, if you want to preserve the original number, formatting just to print, then all you need to do is write your expression within the curly braces of the f-string.myNum = 3.14159265359print(f"My number is {round(myNum,2)}") # My number is 3.14
Conclusion
There we go, a quick and simple guide to kick-off your handling of decimal values. There’s more to mastering decimals, including understanding floating-point numbers and using advanced tools such as the Decimal class, but we’ll save those topics for another day.
I hope this article was helpful, please leave your feedback below and share your experiences working with decimal points in Python.