Python - K length decimal Places


In computer science we define decimal numbers to be the numbers which utilize base10 notations. For example 12,4,5.7,99 are decimal numbers because they utilize base 10 notation. We can define the length of a decimal number as the number of digits present in the decimal number. More precisely, the number of significant figures present in the decimal number includes both digits after and before the decimal parts. This article will explore several methods to find the k−length decimal places like the round method, String formatting, Global precisions, etc.

Using round Method

One of the simplest ways to control the precision of the decimal places is to use the round method. This is an in−built method of Python. It takes two arguments: the numbers we need to round off and the number of decimal places we need to round off.

Syntax

round(number, k)

Here the number is the decimal number, and k is the decimal place we need to round off the number. It returns a decimal number with desired round−off. Note that the round−off will follow the traditional rule of mathematics.

Example

In the following code, we created a function named round_off which takes the decimal number and k (number of decimal places). Under the function, we have used the round method of Python, where we passed the number and k as the arguments. We stored the result in the variable rounded and returned this. We used a number for testing purposes and called the function, passing the necessary parameters. We printed the result utilizing the String formatting. Note that here we have rounded off up to 3 decimal places.

def round_off(number, k):
    rounded = round(number, k)  
    return rounded  
k=3
number=  3.141592653589793
print(f"The number {number} round off to {k} decimal places is: {round_off(number, k)}")

Output

The number 3.141592653589793 round off to 3 decimal places is: 3.142

Using String Formatting

In the previous example, we saw how to use the round method to round off the number. The round method follows the traditional rule of mathematics for computation. However, we may need to round off in slightly different ways. We may need to truncate the number instead of rounding off the number. String formatting is an excellent way to perform this.

Syntax

"%.nf" % number

Here n is the number of decimal places upon which we need to format the decimal places. "number" is the decimal number. Rest are the syntax that we need to follow.

Example

We used the String formatting method in the following example to round off the decimal number. We defined the round_off method, which takes the decimal number and k as the parameters. It is a non void method and returns the formatted String. We used the String formatting notation in Python to format the String.

def round_off(number, k):
    formatted = f"%.{k}f" % number  
    return formatted

k=5
number=  7.7486492653
print(f"The number {number} round off to {k} decimal places is : {round_off(number, k)}")

Output

The number 7.7486492653 round off to 5 decimal places is : 7.74865

Setting Global Precision

By default, there are some differences in how the decimal numbers are handled in the binary format. For example, if you try to run the following command:

print(1.1+2.2) 

You would get 3.3000000000000003 and not 3.3. This is not a bug from Python but due to how the operating system handles binary representation. However, we need to control the precision of the decimal numbers up to good accuracy, where even a very small number is very important. The decimal library can help us in this situation. It provides us with a method to resolve this issue called the getcontext(). We can set the precision of the decimal numbers at the global level.

Example

from decimal import Decimal, getcontext
print(1.1+2.2)
getcontext().prec=16
print(Decimal(1.1)+Decimal(2.2))

Output

3.3000000000000003
3.300000000000000

Using The Numpy Libray

The Numpy is a popular library in Python to perform numerical computations. The library deals with arrays which are list−like objects, with the only difference being they hold homogeneous data types only. The library also provides a method called around which takes the array of numbers and returns the decimal numbers truncated to the specified number.

Example

In the following code, we first imported the Numpy library in the code. Next, we defined the function round_off, which takes the parameter k and **kwargs(variable arguments). Next, we used the list method to convert all the values of the kwargs to the list data type. We used the around method to find the rounded−off decimal numbers of the list of numbers. We passed the list and the decimal as arguments to the function. Finally, we returned the result.

import numpy as np
def round_off(k, **kwargs):
    numbers = list(kwargs.values())
    rounded = np.around(numbers, decimals=k)  
    return rounded
k = 5
numbers = {'num1': 7.7486492653, 'num2': 5.634534534, 'num3': 64.345345345}
rounded_numbers = round_off(k, **numbers)
print(f"The numbers {numbers} rounded off to {k} decimal places are: {rounded_numbers}")

Output

The numbers {'num1': 7.7486492653, 'num2': 5.634534534, 'num3': 64.345345345} rounded off to 5 decimal places are: [ 7.74865  5.63453 64.34535]

Conclusion

In this article, we understood how to find k−length decimal places in Python using several methods available in Python. We used the round method, which is very convenient to use. Next, we used the String formatting method, which is useful for truncating over rounding off the decimal number. The decimal library helps to reduce some of the inconsistencies in the representation of decimal numbers. On the other hand, some other libraries like Numpy also allow us to round off the decimal numbers in an array−like object.

Updated on: 18-Jul-2023

76 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements