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