Become a Python developer and tackle a variety of tasks, from coding to process automation

Exchange insights, tools, and strategies for canada dataset.
Post Reply
rifat28dddd
Posts: 732
Joined: Fri Dec 27, 2024 12:35 pm

Become a Python developer and tackle a variety of tasks, from coding to process automation

Post by rifat28dddd »

Rounding functions from the math module
Before using functions from the math module, this module must first be imported. To do this, at the very beginning of the source code, write:

import math
And now you can safely use any functions from this module. Next, we will look at three functions that are used to round numbers.

Function math.ceil()
This function rounds up. Here is an example:

num = math.ceil ( 6.8 )
print ( num )
Result:

alex@alex-pc:~$ /bin/python3 /home/alex/test.py
7
Function math.floor()
And this function rounds down. Example:

num = math. floor ( 6.8 )
print ( num )
Result:

alex@alex-pc:~$ /bin/python3 /home/alex/test.py
6
Function math.trunc()
This is an analogue of the already discussed int() function. It does the same thing: it discards the fractional part, leaving only the whole number. Example:

num = math. trunc ( 17.231449 )
print ( num )
Result:

alex@alex-pc:~$ /bin/python3 /home/alex/test.py
17
Now let's talk about using another module to round numbers.

The quantize() method from the decimal module
Before using this module, you first need to import it:

import decimal
The quantize() method is used for rounding, which is finland telegram data passed a Decimal object as an argument, indicating the rounding format, i.e. how many decimal places to round to. The method should also be applied to the Decimal object, which indicates which number should be rounded. Example code:

num = decimal. Decimal ( '16.357148' ) . quantize ( decimal. Decimal ( '1.00' ))
print ( num )
Result of execution:

alex@alex-pc:~$ /bin/python3 /home/alex/test.py
16.36
In this case, rounding occurred to two decimal places, which is indicated by the decimal.Decimal( '1.00' ) argument in the quantize() method. Special constants activating various rounding modes can also be passed to this method as a second argument. The ROUND_HALF_EVEN constant is used by default, according to which rounding is performed to the nearest even number. Let's look at the remaining constants below.

Read more
Become a Python developer and tackle a variety of tasks, from coding to process automation
ROUND_CEILING
Round up if there is a non-zero digit to the right of the place. Example code with this constant:

num = decimal. Decimal ( '0.6600001' ) . quantize ( decimal. Decimal ( '1.00' ) , decimal.ROUND_CEILING )
print ( num )
Result of execution:
Post Reply