python - Variable decimal place limit in function set by user? -
i started learning python , writing script converts celsius fahrenheit , vise versa. have main part done want able let user set number of decimals displayed in output... first function contains failed attempt , second set @ 2 decimal places.
def convert_f_to_c(t,xx): c = (t - 32) * (5.0 / 9) print "%.%f" % (c, xx) def convert_c_to_f(t): f = 1.8 * t + 32 print "%.2f" % f print "number of decimal places?" dec = raw_input(">") print "(c) celsius >>> ferenheit\n(f) ferenheit >>> celcius" option = raw_input(">") if option == 'c': cel = int(raw_input("temperature in celcius?")) convert_c_to_f(cel) else: fer = int(raw_input("temperature in ferenheit?")) convert_f_to_c(fer,dec)
num_dec = int(raw_input("num decimal places?") print "%0.*f"%(num_dec,3.145678923678)
in % format strings can use *
feature
afaik there no equivelent method in '{}'.format
method
>>> import math >>> print "%0.*f"%(3,math.pi) 3.142 >>> print "%0.*f"%(13,math.pi) 3.1415926535898 >>>
Comments
Post a Comment