Turbo
Turbo

Reputation: 323

Two Decimals in Python?

I'm trying to make this program which calculates the volume and surface area of a cylinder; I am currently coding the volume part of it. However, in the output screen, there are two decimals. It shows:

The volume of the cylinder is193019.2896193019.2896cm³

Why are there two?

After that, I'm trying to make the program ask the user how many decimal places (d.p.) the user wants. How can I do this?

Here is the current code:

print("Welcome to the volume and surface area cylinder calculator powered by Python!")
response = input("To calculate the volume type in 'vol', to calculate the surface area, type in 'SA': ")
if response=="vol" or response =="SA":
    pass
else:
    print("Please enter a correct statement.")
    response = input("To calculate the volume type in 'vol', to calculate the surface area, type in 'SA': ")

if response=="vol":
    #Below splits 
    radius, height = [float(part) for part in input("What is the radius and height of the cylinder? (e.g. 32, 15): ").split(',')] 
    PI = 3.14159 #Making the constant PI
    volume = PI*radius*radius*height
    print("The volume of the cylinder is" + str(volume) + "{}cm\u00b3".format(volume))

Upvotes: 0

Views: 592

Answers (2)

Hyperboreus
Hyperboreus

Reputation: 32429

To answer your question about asking the user how many decimal he wants:

#! /usr/bin/python3

decimals = int (input ('How many decimals? ') )
print ('{{:.{}f}}'.format (decimals).format (1 / 7) )

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121884

You are interpolating the value twice:

print("The volume of the cylinder is" + str(volume) + "{}cm\u00b3".format(volume))

Just once will do:

print("The volume of the cylinder is {}cm\u00b3".format(volume))

The nice thing about the .format() function is that you can tell it to format your number to a certain number of decimals:

print("The volume of the cylinder is {:.5f}cm\u00b3".format(volume))

where it'll use 5 decimals. That number can be parameterized too:

decimals = 5
print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimals))

Demo:

>>> volume = 193019.2896
>>> decimals = 2
>>> print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimals))
The volume of the cylinder is 193019.29cm³
>>> decimals = 3
>>> print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimals))
The volume of the cylinder is 193019.290cm³

I'll leave using input() and int() to ask for an integer number of decimals from the user up to you.

Upvotes: 9

Related Questions