How to get decimal places in python

Python has several options to round to a whole number. But what if we want to round to a number of decimal digits, like 2 decimal places? Let’s see how we do that.

IN THIS ARTICLE:

  • Round Python values to two decimals places (and more)
  • Round decimal places up and down: round()
    • Example: round decimal digits up and down
  • Round decimal places up in Python
    • Example: round up to 2 decimal places
  • Round decimal places down in Python
    • Example: round down to 2 decimal places
  • Round decimal places of Python lists and arrays
    • Rounds lists to decimal places with a list comprehension
    • Round lists to decimal places with Python’s for loop
    • Round Python arrays to 2 decimal places
    • Round NumPy arrays to two decimal places
  • Summary

# Round Python values to two decimals places (and more)

Though rounding to a whole number is helpful, there are still plenty of situations in which we need to round to a certain number of decimal places. For example, currency is best reported with 2 decimal digits. And error levels and significance often use more digits, like 5.

Python has several ways to round decimal digits:

  • The round() function rounds decimal places up and down. This makes 4.458 into 4.46 and 8.82392 into 8.82.
  • To round decimal places up we have to use a custom function. That way 8.343 becomes 8.35.
  • To round decimal places down we use a custom function. That turns 2.348 into 2.34.

Let’s look at each approach and the Python code they require.

# Round decimal places up and down: round()

With Python’s round() function we can round decimal places up and down. The function needs two arguments for that. The first is the value to round. The second is the number of digits after the decimal point (.) to round to (Lutz, 2013; Sweigart, 2015).

So to round to 2 decimal places we do:

round(12.54673, 2)
# Returns: 12.55

# Example: round decimal digits up and down

To see how round() works in practice, let’s explore the following mini-program:

# Some numerical values
valueA = 3.14159265359
valueB = 1845.7409947
valueC = -100.95
valueD = 9.5432
valueE = 34.49953

# Round to different decimal places
roundA = round(valueA, 5)
roundB = round(valueB, 4)
roundC = round(valueC, 3)
roundD = round(valueD, 2)
roundE = round(valueE, 1)

# Output rounded values
print("Value:".ljust(15), "Rounded:")

print(str(valueA).ljust(15), roundA)
print(str(valueB).ljust(15), roundB)
print(str(valueC).ljust(15), roundC)
print(str(valueD).ljust(15), roundD)
print(str(valueE).ljust(15), roundE)

This code first makes five floating-point variables. Each has several numbers after the decimal point (.). We store their values in variables valueA through valueE.

Then we round each to a number of decimal places. We call the round() function with two arguments. The first is the variable we just made. The second the number of decimals to round to. Here we use values 5 through 1 for that. We store the rounded values in new variables (roundA through roundE).

Then Python’s print() function displays both the original and rounded value. With the ljust() string method we align the original value to the left. That makes for a nice table-like output. As we can see from the output, each value is rounded correctly:

Value:          Rounded:
3.14159265359   3.14159
1845.7409947    1845.741
-100.95         -100.95
9.5432          9.54
34.49953        34.5

# Round decimal places up in Python

Another option is to always round a number’s decimal digits up. That’s for instance what companies do: rather than round prices up or down, values like 4.5421 are instead always rounded up to $4.55.

Python, however, doesn’t have a built-in function for that. But we can make our own and leverage the math.ceil() function. When we do, using the function looks like this:

round_decimals_up(8.343)
# Returns: 8.35

Here’s how we code that round_decimals_up() function:

import math


def round_decimals_up(number:float, decimals:int=2):
    """
    Returns a value rounded up to a specific number of decimal places.
    """
    if not isinstance(decimals, int):
        raise TypeError("decimal places must be an integer")
    elif decimals < 0:
        raise ValueError("decimal places has to be 0 or more")
    elif decimals == 0:
        return math.ceil(number)

    factor = 10 ** decimals
    return math.ceil(number * factor) / factor

This function has two parameters: the value to round (number) and how many decimal places it should get (decimals). When that latter parameter isn’t set, it defaults to 2.

The function’s code has two parts. The first validates and handles the decimals parameter. The second performs the actual rounding.

For that validation we use Python’s cascaded if statement. The first condition has isinstance() see if the decimals parameter is something else than an integer (int). When it is, we generate a TypeError to notify the user that the function is used in the wrong way.

Next we check if decimals is under (<) zero. Since the function doesn’t know how to handle negative decimal places, we trigger a ValueError to communicate this to the function’s user.

The final elif test sees if the decimals parameter equals (==) 0. When the function has to round a value up without decimal places, we can simply execute the math.ceil() function and round to a whole number.

Then we get to the second part of the function. This is where we do the actual rounding to decimal places. But first we determine the correction factor. To get that value we raise 10 to the power of the decimals parameter. We store the outcome in the factor variable.

Next we call the math.ceil() function. Inside its parentheses we specify the value to round up (number) multiplied with factor. We then divide the rounded result with factor to get the proper number of decimal places back.

Say the function should round 23.4249 to 2 decimal places. The code then first multiplies 23.4249 with 100 (102). math.ceil() then rounds 2342.49 up to an integer (2343). Finally we divide back with 100 to get the result in two decimal digits: 23.43.

# Example: round up to 2 decimal places

To see how interacting with that custom round_decimals_up() function goes, let’s use it in a mini-program:

import math


def round_decimals_up(number:float, decimals:int=2):
    """
    Returns a value rounded up to a specific number of decimal places.
    """
    if not isinstance(decimals, int):
        raise TypeError("decimal places must be an integer")
    elif decimals < 0:
        raise ValueError("decimal places has to be 0 or more")
    elif decimals == 0:
        return math.ceil(number)

    factor = 10 ** decimals
    return math.ceil(number * factor) / factor


# Some numbers to round
valueA = 3.14159265359
valueB = 1845.7409947
valueC = -100.95
valueD = 9.5432
valueE = 34.49953

# Round to values to a different number of decimal places
roundA = round_decimals_up(valueA)
roundB = round_decimals_up(valueB)
roundC = round_decimals_up(valueC)
roundD = round_decimals_up(valueD)
roundE = round_decimals_up(valueE)

# Output the results
print("Value:".ljust(15), "Rounded:")

print(str(valueA).ljust(15), roundA)
print(str(valueB).ljust(15), roundB)
print(str(valueC).ljust(15), roundC)
print(str(valueD).ljust(15), roundD)
print(str(valueE).ljust(15), roundE)

This program first imports the math module. That makes the math.ceil() function available for our custom function, which we copy/paste into the program next.

Then we make five variables (valueA through valueE). Each has a floating-point value with a couple of decimal digits. Let’s round their values.

For that we call the round_decimals_up() function repeatedly. We provide it with one argument: the value to round. The function then automatically uses two decimal places for its rounding. We put the rounded values in variables roundA through roundE.

The print() function then outputs the original and rounded value. This is how the function rounded every variable up to two decimal places:

Value:          Rounded:
3.14159265359   3.15
1845.7409947    1845.75
-100.95         -100.95
9.5432          9.55
34.49953        34.5

# Round decimal places down in Python

The third way to handle decimal digits is to always round down. This is what a strict teacher might use: rather than round 8.18 and 5.95 up, he or she instead rounds down to 8.1 and 5.9.

There’s no built-in function in Python for that kind of rounding. But we can build our own and leverage the math.floor() function. Using such a custom function looks like:

round_decimals_down(2.348, 2)
# Or:
round_decimals_down(2.348)
# Both return: 2.34

That works nicely. Now let’s code that custom function:

import math


def round_decimals_down(number:float, decimals:int=2):
    """
    Returns a value rounded down to a specific number of decimal places.
    """
    if not isinstance(decimals, int):
        raise TypeError("decimal places must be an integer")
    elif decimals < 0:
        raise ValueError("decimal places has to be 0 or more")
    elif decimals == 0:
        return math.floor(number)

    factor = 10 ** decimals
    return math.floor(number * factor) / factor

Much of this function is the same as the other custom function (round_decimals_up()) we already discussed earlier.

The main difference is that we now use the math.floor() function. This function rounds the number parameter multiplied with the factor variable down. Then we divide again with factor to get the right number of decimal places.

Say we ask the function to round 483.749 down to 2 decimal digits. The code then first multiplies that value with 100. math.floor() then rounds 48374.9 down to a whole number (48374). When we divide back with 100 we get the proper number of decimal places: 483.74.

# Example: round down to 2 decimal places

Let’s see how that above function works in practice. This mini-program has the function round down 5 different values:

import math


def round_decimals_down(number:float, decimals:int=2):
    """
    Returns a value rounded down to a specific number of decimal places.
    """
    if not isinstance(decimals, int):
        raise TypeError("decimal places must be an integer")
    elif decimals < 0:
        raise ValueError("decimal places has to be 0 or more")
    elif decimals == 0:
        return math.floor(number)

    factor = 10 ** decimals
    return math.floor(number * factor) / factor


# Some numbers to round
valueA = 3.14159265359
valueB = 1845.7409947
valueC = -100.95
valueD = 9.5432
valueE = 34.49953

# Round values to a certain number of decimal places
roundA = round_decimals_down(valueA, 5)
roundB = round_decimals_down(valueB, 4)
roundC = round_decimals_down(valueC, 3)
roundD = round_decimals_down(valueD, 2)
roundE = round_decimals_down(valueE, 1)

# Display the results
print("Value:".ljust(15), "Rounded:")

print(str(valueA).ljust(15), roundA)
print(str(valueB).ljust(15), roundB)
print(str(valueC).ljust(15), roundC)
print(str(valueD).ljust(15), roundD)
print(str(valueE).ljust(15), roundE)

First we import the math module. That way the custom round_decimals_down() function can use math.floor(). We then insert that custom function.

Then we make five variables (valueA through valueE). Each hold a value with decimals to round down. That rounding is what we do next.

So we repeatedly execute round_decimals_down(). Each time we give the function two arguments: the value to round and the number of decimal digits to keep. We put the results in new variables (roundA through roundE).

The last bit of code outputs the results with the print() function. We left-align the original value with the ljust() method, and include the rounded value as well. As the output displays, each value is rounded down to a certain number of decimal places:

Value:          Rounded:
3.14159265359   3.14159
1845.7409947    1845.7409
-100.95         -100.95
9.5432          9.54
34.49953        34.4

# Round decimal places of Python lists and arrays

The above examples always rounded one value at a time. Sometimes, however, we have a sequence with values we want to round to a number of decimal digits. Let’s see how to do so in Python.

# Rounds lists to decimal places with a list comprehension

One option is to round every value with a list comprehension. This requires just a bit of code and runs efficiently. A list comprehension works best when your code isn’t that complex. Simply rounding values meets that mark.

Here’s a quick example:

# Some list with values
values = [22.459, 5.963, 2.335]

# Round each value to 2 decimal places
rounded = [round(value, 2) for value in values]

The rounded list we make here gets its values from a list comprehension. That comprehension executes the round(value, 2) expression for every value generated by the in-line for loop: for value in values. That’s how we go through the original values list one element at a time.

Here’s a mini-program that rounds every value in a list:

import math


def round_decimals_down(number:float, decimals:int=2):
    """
    Returns a value rounded down to a specific number of decimal places.
    """
    if not isinstance(decimals, int):
        raise TypeError("decimal places must be an integer")
    elif decimals < 0:
        raise ValueError("decimal places has to be 0 or more")
    elif decimals == 0:
        return math.floor(number)

    factor = 10 ** decimals
    return math.floor(number * factor) / factor


def round_decimals_up(number:float, decimals:int=2):
    """
    Returns a value rounded up to a specific number of decimal places.
    """
    if not isinstance(decimals, int):
        raise TypeError("decimal places must be an integer")
    elif decimals < 0:
        raise ValueError("decimal places has to be 0 or more")
    elif decimals == 0:
        return math.ceil(number)

    factor = 10 ** decimals
    return math.ceil(number * factor) / factor


# Some random values
values = [
    22.459, 5.963, 2.335,
    -1.569, -0.019, -22.3
]

# Make new lists, with the original values rounded to 2 decimals
valuesRound = [round(value, 2) for value in values]
valuesUp = [round_decimals_up(value, 2) for value in values]
valuesDown = [round_decimals_down(value) for value in values]

# Output results
print("Original values:\n", values)
print("Rounded to 2 decimals:\n", valuesRound)
print("Rounded up to 2 decimals:\n", valuesUp)
print("Rounded down to 2 decimals:\n", valuesDown)

We first import the math module. Then we insert the round_decimals_down() and round_decimals_up() functions we made earlier in this article.

Next we make a list with numbers. That values list has 6 floating-point values. Then we round each value in that list. We use three different list comprehensions for that.

The first rounds every list value to two decimal places (up and down) with the round() function. We put those rounded values in a new list, valuesRound.

The second list comprehension has the round_decimals_up() function round up to two decimal digits. The new list that this returns is what we store in valuesUp. The third and last list comprehension rounds down to two decimal places (round_decimals_down()). The results of that comprehension are stored in the valuesDown list.

The program’s last bit of code outputs all four lists with the print() function. This is how those rounded values look like:

Original values:
 [22.459, 5.963, 2.335, -1.569, -0.019, -22.3]
Rounded to 2 decimals:
 [22.46, 5.96, 2.33, -1.57, -0.02, -22.3]
Rounded up to 2 decimals:
 [22.46, 5.97, 2.34, -1.56, -0.01, -22.3]
Rounded down to 2 decimals:
 [22.45, 5.96, 2.33, -1.57, -0.02, -22.3]

In the above example we made new lists with the list comprehension. If you don’t need to keep the original list values, then a list comprehension can also overwrite the existing list. To do so we set the list’s value to the outcome of the list comprehension:

# Round every number in the 'values' list to 3
# decimal places, replacing the original numbers
values = [round(value, 3) for value in values]

# Round lists to decimal places with Python’s for loop

The second way to round list values is with a for loop. This requires a bit more code than a list comprehension does, but has more capabilities and is easier to read in complex situations.

As a quick example:

# List with values
values = [22.459, 5.963, 2.335]

# Make a new list to hold the results
values_rounded = []

# Go through the original list and fill
# the new list with rounded values
for value in values:
    values_rounded.append(round(value, 2))

The values_rounded list we make here starts empty ([]). But inside the for loop we fill that list with values. For that we call the append() method on the list, and pass in the rounded value from the original list (round(value, 2)).

This mini-program rounds list values with for:

import math


def round_decimals_down(number:float, decimals:int=2):
    """
    Returns a value rounded down to a specific number of decimal places.
    """
    if not isinstance(decimals, int):
        raise TypeError("decimal places must be an integer")
    elif decimals < 0:
        raise ValueError("decimal places has to be 0 or more")
    elif decimals == 0:
        return math.floor(number)

    factor = 10 ** decimals
    return math.floor(number * factor) / factor


def round_decimals_up(number:float, decimals:int=2):
    """
    Returns a value rounded up to a specific number of decimal places.
    """
    if not isinstance(decimals, int):
        raise TypeError("decimal places must be an integer")
    elif decimals < 0:
        raise ValueError("decimal places has to be 0 or more")
    elif decimals == 0:
        return math.ceil(number)

    factor = 10 ** decimals
    return math.ceil(number * factor) / factor


# Some random values
values = [
    22.459, 5.963, 2.335,
    -1.569, -0.019, -22.3
]

# Make new lists that hold the results
valuesRound = []
valuesUp = []
valuesDown = []

# Loop through the original values and populate
# the new lists with rounded values
for value in values:
    valuesRound.append(round(value, 2))
    valuesUp.append(round_decimals_up(value, 2))
    valuesDown.append(round_decimals_down(value, 2))

# Output data
print("Original values:\n", values)
print("Rounded up and down to 2 decimals:\n", valuesRound)
print("Rounded up to 2 decimals:\n", valuesUp)
print("Rounded down to 2 decimals:\n", valuesDown)

We again first import the math module. Then we copy/paste the round_decimals_down() and round_decimals_up() functions that we made earlier in this article.

After that we make a list with several floating-point values, both positive and negative. Then we code three empty lists ([]): valuesRound, valuesUp, and valuesDown. These are going to hold the rounded values.

To make that happen we create a for loop. This loop iterates through every value in the values list. During each loop cycle, the current list value gets accessed with the value loop variable. Inside that loop we append a rounded value to each of the three lists with Python’s append() method.

The program’s last bit of code then outputs the original list and its rounded derivatives. Here’s what that displays:

Original values:
 [22.459, 5.963, 2.335, -1.569, -0.019, -22.3]
Rounded up and down to 2 decimals:
 [22.46, 5.96, 2.33, -1.57, -0.02, -22.3]
Rounded up to 2 decimals:
 [22.46, 5.97, 2.34, -1.56, -0.01, -22.3]
Rounded down to 2 decimals:
 [22.45, 5.96, 2.33, -1.57, -0.02, -22.3]

Have no need for the original list values? In that case you don’t have to make a new, separate list. Instead you can overwrite the existing one in place. A helpful function for that is Python’s enumerate(). For example:

# Loop through the original 'values' list, and
# round each value to 2 decimal places
for index, value in enumerate(values):
    values[index] = round(value, 2)

# Round Python arrays to 2 decimal places

Of course we can also round other collections than lists. Here’s how we round every value in a Python array to 2 decimal places:

from array import array

# Make an array with double-precision float values
values = array('d', [3.14159265359, 1845.7409947, 9.5432, -34.49953])

# Make a new array with values rounded to 2 decimals
rounded = array('d', [round(value, 2) for value in values])

# Output data
print("Original array values:\n", values)
print("Rounded to 2 decimal digits:\n", rounded)

First we import the array() constructor from the array module. Then we make an array with floating-point values. We name that array values.

Then we build a second array. This one has the values from the original array rounded to 2 decimal places. To make that happen we use a list comprehension. That rounds each value to two decimal digits (round(value, 2)). We name that new, rounded array rounded.

The print() function then outputs the original and rounded array. As we can tell, each value is properly rounded to two decimal places:

Original array values:
 array('d', [3.14159265359, 1845.7409947, 9.5432, -34.49953])
Rounded to 2 decimal digits:
 array('d', [3.14, 1845.74, 9.54, -34.5])

Don’t need to keep the original array values? In that case you can overwrite the existing array with its rounded values. Here’s how:

# Make an array with float values
values = array('d', [3.14159265359, 1845.7409947, 9.5432, -34.49953])

# Overwrite the array with rounded values
values = array('d', [round(value, 2) for value in values])

# Round NumPy arrays to two decimal places

Of course we can also round the values of other arrays. One example are those from the NumPy numeric programming package for Python. To round a NumPy array to two decimal places we do:

import numpy

# Create a NumPy array
values = numpy.array([3.14159265359, 1845.7409947, 9.5432, -34.49953])

# Make a new array with rounded values
rounded = numpy.round(values, 2)

# Output data
print("Original NumPy array values:\n", values)
print("NumPy array rounded to 2 decimals:\n", rounded)

We first import the numpy module. Then we make a NumPy array with the numpy.array() function. That array has several floating-point values.

Then we round the original array to two decimal digits. For that we call the numpy.round() function with two arguments. The first is the array with values to round. The second is the number of decimal places to round to. We store the array the function returns in the rounded variable.

The last bit of code outputs both the original and rounded array. That shows how the values are nicely rounded to 2 decimal places:

Original NumPy array values:
 [   3.14159265 1845.7409947     9.5432      -34.49953   ]
NumPy array rounded to 2 decimals:
 [   3.14 1845.74    9.54  -34.5 ]

The numpy.round() function rounds up and down. To always round up or to always round down we have to use the custom round_decimals_up() and round_decimals_down() functions.

When we use those functions in a list comprehension, they can round each value from a NumPy array. For example:

# Create an array with floating-point values
values = numpy.array([3.14159265359, 1845.7409947, 9.5432, -34.49953])

# Round the NumPy array up and down to 2 decimal places
roundUp = numpy.array([round_decimals_up(value, 2) for value in values])
roundDown = numpy.array([round_decimals_down(value, 2) for value in values])

READ MORE

  • Round Python values to a whole number.
  • Truncate Python values to a whole number
  • Truncate to a certain number of decimal places in Python

# Summary

There are three ways to round numbers to a certain number of decimal places. To round up and down we use Python’s round() function. The first argument we give that function is the number to round. The second argument the number of decimal places to round to.

Python has no function that always rounds decimal digits up (9.232 into 9.24). But when we leverage the math.ceil() function in a custom function, we can easily implement that ourselves.

There’s neither a function that always rounds decimal digits down (3.458 becomes 3.45). But when we wrap the math.floor() function in a custom function we can create that behaviour ourselves.

To round every value in a list or array we can use a list comprehension or for loop. The first is compact and the second easier to work with.

References

Lutz, M. (2013). Learning Python (5th Edition). Sebastopol, CA: O’Reilly Media.

Sweigart, A. (2015). Automate The Boring Stuff With Python: Practical Programming for Total Beginners. San Francisco, CA: No Starch Press.

Python.org (n.d.). Built-in Functions. Retrieved on November 8, 2019, from https://docs.python.org/3/library/functions.html

Last updated on September 9, 2020 (published December 20, 2019).

« All Python math articles

How do you get 2 decimal places in Python?

Use str. format() with “{:. 2f}” as string and float as a number to display 2 decimal places in Python. Call print and it will display the float with 2 decimal places in the console.

How do you get 3 decimal places in Python?

Use the round() function to round a float to 3 decimal places, e.g. result = round(6.36789, 3) . The round() function will round the floating-point number to 3 decimal places and will return the result.

How do you get 5 decimal places in Python?

“how to have 5 decimal places in python” Code Answer's.
>>> x = 13.949999999999999999..
>>> x..
13.95..
>>> g = float("{0:.2f}". format(x)).
>>> g..
13.95..
>>> x == g..

How do I print 6 decimal places in Python?

Use the round() function to print a float to 6 decimal places, e.g. print(round(my_float, 6)) . The round() function will round the floating-point number to 6 decimal places and will return the result.