Open In App

Python – K length decimal Places

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Python, controlling the number of decimal places in your numeric values is essential for presenting results accurately and efficiently. This article explores techniques to manage K-length decimal places in Python. Given a Decimal Number, extend its digits to K length.

Input: num = 76.8, K = 5 
Output: 76.80000
Explanation: Length of decimal places is 5.
Input: num = 76.8, K = 6
Output: 76.800000
Explanation: Length of decimal places is 6.


Find K-length decimal Places using Format() 

Python’s format() function allows specifying decimal places for numeric values. This is the way in which this task can be done. In this, we harness multiple format compatibilities to perform the task of getting the appropriate length of decimal places.

Python3
num = 76.8

# printing original number
print("The original number is : " + str(num))

# initializing K
K = 7

# using format to solve this problem
res = "{{:.{}f}}".format(K).format(num)

print("The resultant number : " + str(res))

Output:

The original number is : 76.8
The resultant number : 76.8000000


Find K-length decimal Places using f-string

Python’s f-stringallows specifying decimal places for numeric values. First Define a function format_decimal_places that takes a number num and an integer K as inputs. Inside the function, use an f-string to format the number with the specified number of decimal places K. And it will Return the formatted number.

Python3
def format_decimal_places(num, K):
    formatted_num = f"{num:.{K}f}"
    return formatted_num

num = 76.8
K = 5
output = format_decimal_places(num, K)
print(output)

Output:

76.80000


Find K-length decimal Places using str(),index() and len() methods

In Python you can find K-length decimal places in a floating-point number using a combination of string manipulation methods such as str(), index(), and len().

Python3
num = 76.8

# printing original number
print("The original number is : " + str(num))

# initializing K
K = 7
num = str(num)
x = num[num.index(".")+1:]
y = "0"*(K-len(x))
res = num+y

print("The resultant number : " + str(res))

Output:

The original number is : 76.8
The resultant number : 76.8000000


Find K-length decimal Places using Round() Function

Python’s round() function to find K-length decimal places in a floating-point number involves rounding the number to K decimal places and then converting it back to a string to obtain the desired representation.

Python3
def find_k_decimal_places(num, k):
    rounded_num = round(num, k)
    rounded_str = str(rounded_num)
    decimal_index = rounded_str.index('.')
    return rounded_str[decimal_index + 1:]

# Example usage
value = 9.99999
k = 4
result = find_k_decimal_places(value, k)
print(result)

Output:

0

Find K-length decimal Places using the ‘Decimal’ class

  • Define the function decimal_class_decimal(num, k).
  • Convert the floating-point number num to a Decimal object using Decimal(str(num)).
  • Use the quantize() method to round the Decimal number to k decimal places with ROUND_HALF_UP rounding mode: .quantize(Decimal(f”1e-{k}”), rounding=ROUND_HALF_UP).
  • Return the quantized Decimal number.
  • Set initial values for num and k: num = 76.8 and k = 5.
  • Call the decimal_class_decimal function with the given values: result = decimal_class_decimal(num, k).
  • Print the result: print(result).
Python3
from decimal import Decimal, ROUND_HALF_UP

def decimal_class_decimal(num, k):
    # Convert the floating-point number 'num' to a Decimal object
    decimal_num = Decimal(str(num))
    
    # Quantize the Decimal number to 'k' decimal places using ROUND_HALF_UP rounding mode
    decimal_num = decimal_num.quantize(Decimal(f"1e-{k}"), rounding=ROUND_HALF_UP)
    
    # Return the quantized Decimal number
    return decimal_num

# Example usage:
# Set the initial values for 'num' and 'k'
num = 76.8
k = 5

# Call the 'decimal_class_decimal' function with the given values
result = decimal_class_decimal(num, k)

# Print the result
print(result)

Output
76.80000

Time Complexity: O(d + k)

Auxiliary Space Complexity: O(d + k)




Similar Reads

Python | Get a set of places according to search query using Google Places API
Google Places API Web Service allow the user to query for place information on a variety of categories, such as establishments, prominent points of interest, geographic locations, and more. One can search for places either by proximity or a text string. A Place Search returns a list of places along with summary information about each place; additio
3 min read
Calculate distance and duration between two places using google distance matrix API in Python
Google Map Distance Matrix API is a service that provides travel distance and time is taken to reach a destination. This API returns the recommended route(not detailed) between origin and destination, which consists of duration and distance values for each pair. To use this API, one must need the API key, which can be get form here. Modules needed
2 min read
Python | Calculate geographic coordinates of places using google geocoding API
Geocoding is the process of converting addresses into geographic coordinates like latitude and longitude, which can be used to mark position on map.To use the Google Maps Geocoding API, one must need an API key, which can be get form here. Modules needed : Below is the implementation : C/C++ Code # Python program to calculate geographic # coordinat
2 min read
Python | Calculate Distance between two places using Geopy
GeoPy is a Python library that makes geographical calculations easier for the users. In this article, we will see how to calculate the distance between 2 points on the earth in two ways. How to Install GeoPy ? pip install geopy Geodesic Distance: It is the length of the shortest path between 2 points on any surface. In our case, the surface is the
1 min read
Build a GUI Application to get distance between two places using Python
Prerequisite: Tkinter In this article, we are going to write a python script to get the distance between two places and bind it with the GUI application. To install the GeoPy module, run the following command in your terminal. pip install geopy Approach used: Import the geopy module.Initialize Nominatim API to get location from the input string.Get
2 min read
Python3 Program for Check if a string can be obtained by rotating another string d places
Given two strings str1 and str2 and an integer d, the task is to check whether str2 can be obtained by rotating str1 by d places (either to the left or to the right). Examples: Input: str1 = "abcdefg", str2 = "cdefgab", d = 2 Output: Yes Rotate str1 2 places to the left. Input: str1 = "abcdefg", str2 = "cdfdawb", d = 6 Output: No Approach: An appro
3 min read
Python3 Program to Rotate the sub-list of a linked list from position M to N to the right by K places
Given a linked list and two positions 'm' and 'n'. The task is to rotate the sublist from position m to n, to the right by k places. Examples: Input: list = 1->2->3->4->5->6, m = 2, n = 5, k = 2 Output: 1->4->5->2->3->6 Rotate the sublist 2 3 4 5 towards right 2 times then the modified list are: 1 4 5 2 3 6 Input: list
4 min read
Python3 Program to Check if a string can be obtained by rotating another string 2 places
Given two strings, the task is to find if a string can be obtained by rotating another string two places. Examples: Input: string1 = "amazon", string2 = "azonam" Output: Yes // rotated anti-clockwiseInput: string1 = "amazon", string2 = "onamaz" Output: Yes // rotated clockwise Asked in: Amazon Interview Recommended: Please solve it on “PRACTICE ” f
2 min read
Python string length | len() function to find string length
The string len() function returns the length of the string. In this article, we will see how to find the length of a string using the string len() method. Example: C/C++ Code string = "Geeksforgeeks" print(len(string)) Output13String len() Syntax len(string) Parameter String: string of which you want to find the length. Return: It returns
3 min read
Convert Decimal to Other Bases in Python
Given a number in decimal number convert it into binary, octal and hexadecimal number. Here is function to convert decimal to binary, decimal to octal and decimal to hexadecimal. Examples: Input : 55 Output : 55 in Binary : 0b110111 55 in Octal : 0o67 55 in Hexadecimal : 0x37 Input : 282 Output : 282 in Binary : 0b100011010 282 in Octal : 0o432 282
2 min read
Article Tags :
Practice Tags :