Skip to content
Related Articles
Open in App
Not now

Related Articles

Python – K length decimal Places

Improve Article
Save Article
  • Last Updated : 16 Nov, 2022
Improve Article
Save Article

Given a Decimal Number, extent 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.

Method : Using format() 

This is way in which this task can be done. In this, we harness multiple format compatibilities to perform task of getting appropriate length of decimal places.

Python3




# Python3 code to demonstrate working of
# K length decimal Places
# Using format()
 
# initializing number
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)
 
# printing result
print("The resultant number : " + str(res))

Output

The original number is : 76.8
The resultant number : 76.8000000

Method : Using str(),index() and len() methods

Python3




# Python3 code to demonstrate working of
# K length decimal Places
 
# initializing number
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
 
# printing result
print("The resultant number : " + str(res))

Output

The original number is : 76.8
The resultant number : 76.8000000

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!