Round to 2 decimal places
MRAB
python at mrabarnett.plus.com
Wed Dec 6 21:09:25 EST 2017
On 2017-12-07 01:39, nick martinez via Python-list wrote:
> On Wednesday, December 6, 2017 at 8:13:36 PM UTC-5, ssghot... at gmail.com wrote:
>> The following works:
>>
>> import math
>>
>> print("This program will calculate the surface area and volume of a 3-dimensional cone: ")
>> print()
>> print()
>> r = input("What is the radius in feet? (no negatives): ")
>> h = input("What is the height in feet? (no negatives): ")
>> r = float(r)
>> h = float(h)
>> if r > 0 and h > 0:
>>
>> surfacearea = math.pi * r ** 2 + r * math.pi * (math.sqrt(r ** 2 + h ** 2))
>> volume = (1 / 3) * math.pi * r ** 2 * h
>>
>> print()
>> print("Your Answer is:")
>> print()
>>
>> print("A cone with radius", r, "\nand height of", h, "\nhas a volume of : ", round(volume,2), "\nand surface area of : ",
>> round(surfacearea,2), )
>> else:
>> print("No negatives allowed, try again.")
>
> Tried this but it doesn't seem to work. It still prints out all of the decimals
>
Try using .format:
print("A cone with radius {}\nand height of {}\nhas a volume of :
{:.2f}\nand surface area of : {:.2f}".format(r, h, volume, surfacearea)))
round(volume,2) will round the volume to 2 decimal places, but
floating-point numbers in Python are stored in binary, and you can't
always represent a fractional decimal number exactly in binary. For
example, you can't store 0.1 exactly as a float.
More information about the Python-list
mailing list