Rounding down in python

Round Down Numbers in Python (With Examples and Code)

Round Down Numbers in Python (With Examples and Code)

Do you know it is easier to remember 10 than 9.8 or 10.2? Why? Because whole numbers are easier to work with than decimals.

Rounding off is the most basic yet essential part of programming.

Rounding is the practice of simplifying a number without modifying much of its value. For instance, 9.8 rounded to 10, with only a 0.2 difference. Likewise, 10.2 rounded to 10, with the same difference. So the only goal is to get a value that is close to the original value but in a simpler form. Let’s dive deeper into rounding down in Python!

What is round down?

So far, we’ve discussed «Round off,» which is the most general type of approximation. «Round down,» while similar, is not the same. As the name implies, Round Down reduce a number to the nearest lower integer.

For example —

The above table is an overview of how rounding down values works.

You might be wondering, how is this different from Round up?

It’s quite simple. Round Up, as the name implies, rounds the value to the nearest higher integer, whereas Round Down rounds the value to the nearest lower integer.

Look at the diagram below. You can also think of it as Round up going to the right of the number line while Round down moves towards the left.

Round up vs round down example

Now that we know what Round Down is, let’s look at how to round down values in programming.

How to Round Down a Number in Python?

There are various methods to round down a number in python. Let’s take a look at them.

Method 1: Using string format

This method is applicable when you only want to show the whole number before the decimal point without altering the value. This method only displays the whole number and does not round down the value.

def roundDown(n): return int("".format(n)) roundedValue = roundDown(2.5) print("The rounded value of <> is: <>".format(2.5, roundedValue)) print("Data type of the rounded Value: ", type(roundedValue))
The rounded value of 2.5 is: 2 Data type of the rounded Value: class 'int'> 

Method 2: Using int() method

The int() method terminates the fractional values by returning a whole number. This method converts the given number’s data type to an integer.

# Round down number using int() method number = 10.5 print(int(number)) number = -4.6 print(int(number))

It is worth noting that when dealing with negative numbers, it returns the number away from zero.

Method 3: Using in-built round() method

Python has an in-built round() method to round off any number.
It takes two parameters as input —

  1. num — The number to be rounded.
  2. decimal_places — The number of digits to be rounded off (default being 0).

Let’s try rounding off a number for different decimal places —

# Round down number using round() method number = 12.345 # Here, by default, decimal_places = 0 print(number," rounded till 0 decimal places, (i.e. number as a whole number): ",round(number)) # decimal_places = 1 print(number, " rounded till first decimal point: ", round(number, 1)) # decimal_places = 2 print(number, " rounded till 2 decimal places: ", round(number, 2)) # Surprise element!! print(round(number, -1)) # round() also works with negative decimal_places 

(Attention!!) Although the round() method has made rounding off easier, it doesn’t always «round down» the number (Remember the difference between round up and round down).

12.345 rounded till 0 decimal places, (i.e. number as a whole number): 12 12.345 rounded till first decimal point: 12.3 12.345 rounded till 2 decimal places: 12.35 10.0 

Is it hard to figure out? No worries, let’s walk through this with the help of a table-

Number Decimal places to be rounded off to Output
12.345 0 12
12.345 1 12.3
12.345 2 12.35
12.345 -1 10.0

It’s pretty simple to observe now, isn’t it? Data tabularization is always effective 😉

Method 4: Using trunc() method

The truncate method, also known as trunc(), is a built-in method of the math module. This method returns the integer part of a given decimal number. trunc(), as the name implies, shortens the number rather than rounding it up. Sometimes truncating the number is a better solution for «Round Down in Python».

# Round down number using trunc() method # I've directly imported the trunc() method from math module from math import trunc number = 5.25 print(trunc(number)) number = 7.89 print(trunc(number))

Confused with the direct import? You can always try the following code:-

import math number = 5.25 print(math.trunc(number)) number = 7.89 print(math.trunc(number))

(Ps: Both the code practically indicate the same thing and has the same output)

Method 5: Using math.floor() method

The floor() method is also part of the math module. This method returns the nearest integer that is less than or equal to a given number.
See the syntax below:

# Round down using floor() method # I've directly imported floor() method from math module from math import floor number = 5 print(number, " round down to: ", floor(number)) number = 7.9 print(number, " round down to: ", floor(number)) number = -0.6 print(number, " round down to: ", floor(number))

You can always try the below alternate code:

# Round down using math.floor() method import math number = 5 print(number, " round down to: ", math.floor(number)) number = 7.9 print(number, " round down to: ", math.floor(number)) number = -0.6 print(number, " round down to: ", math.floor(number))

Both the codes above will yield the same output.

5 round down to: 5 7.9 round down to: 7 -0.6 round down to: -1 

From the above code, you can note how the floor() method works with negative numbers. It rounds down the negative number away from zero (Here, -0.6 to 1).

Method 6: Using // operator

Python’s floor division operator, aka the integer division operator, is like math.floor() method . It divides the first number by the second and then rounds down the result to the nearest lower integer. You can always compare its similarity with the floor() method.
Sample code:

# Round Down using floor division operator number = 2.586 print(number // 1) #Dividing it with 1 to get the whole number 

Method 7: Using decimal module (.quantize() method)

Python includes a decimal module for dealing with decimal numbers. It enables easy representation and precision. Using the .quantize() method, we can round off a number. But before using the methods, an instance of the Decimal class must be created.
Too large to handle? Don’t worry, the code below will help you understand-

from decimal import * print(getcontext())

The above lines of code display the properties of a decimal instance.

Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])

You’ll notice that by default, rounding = ‘ROUND_HALF_EVEN». Now to begin with the round-down process —

# Round down using Decimal module #decimal module imported import decimal #changing the rounding property in .getcontext() to 'ROUND_FLOOR' for round down decimal.getcontext().rounding = "ROUND_FLOOR" dec = decimal.Decimal(2.8).quantize(decimal.Decimal(1.0)) #decimal.Decimal(number) creates an instance of Decimal #The decimal.Decimal(1.0) passed as an argument in .quantize() method # determines the number of decimal places to be rounded print(dec) #printing the final rounded result 

Look how this lengthy piece of code produced a one-line output! That’s why the use of decimal module is preferred when dealing with actual decimal or float numbers, else it only adds up to the lines of code.

Other Python modules, such as NumPy and Pandas, provide round down functionality. But, as with the decimal module, these are also preferred when working with large data sets.

Round Down Array Elements in Python

Any of the above-listed methods can be used to round down a number. There are two ways to apply these methods in an array —

Method 1: Using forloop

Using a for loop is the easiest way to round down all the array elements. You can easily iterate through each array element, applying the round down method individually.
See through the below code for a better understanding —

#Round Down an array using math.floor() method from math import floor # a random array of numbers numbers = [3, 2.544, 54.56, 37.566, 1.55, -1, -0.6] #iterating over the array using enumerate for index ,element in enumerate(numbers): numbers[index] = floor(element) #Print the final result print(numbers)

Here, math.floor() method is applied to each element of the array, and is stored back at the same index.

Method 2: Using list comprehension

Compressing the for loop reduces the lines of code, along with increasing the readability of the code. The array can be rounded down using list comprehension as-

#Round Down an array using math.floor() method from math import floor # a random array of numbers numbers = [3, 2.544, 54.56, 37.566, 1.55, -1, -0.6] #Storing the round down values in list result result = [floor(x) for x in numbers] #Print the final result print(result)

Note that the obtained result is the same, irrespective of the way used.

Conclusion

In this article, we have covered various methods to round down in python. When working with data and numbers, you are bound to come across round down, whether working with float numbers or obtaining whole numbers as output. We have understood several methods to round down in python along with their needs. We hope you select the method as per the requirement.

Источник

Читайте также:  Java is required ошибка
Оцените статью