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