Formatted Strings For Rounding In Python
Solution 1:
deffahrenheit_to_celsius(t, p):
celsius = (t - 32.) * 5. / 9.return"{0:.{1}f}".format(celsius, p)
print fahrenheit_to_celsius(76.2, 2) # prints "24.56"print fahrenheit_to_celsius(0, 0) # prints "-18"
Solution 2:
>>>deff_to_c(t, p=0):...returnround(((t - 32.0) * 5.0 / 9.0), p)...>>>print("{}".format(f_to_c(10, 2)))
-12.22
Solution 3:
In the format specifier, add .*
between %
and f
. '.'
specifying decimals, '*'
specifying width to be picked from argument list.
deffahrenheit_to_celsius(t, p):
celsius = ((t - 32.0) * 5.0 / 9.0)
print"%.*f"%(p,celsius) ## pick width from argument.print"%.2f"%(celsius) ## always 2 decimals
From the printf
manual page:
The field width
An optional decimal digit string (with non-zero first digit) specifying a minimum field width. If the converted value has fewer characters than the field width, it will be padded with spaces on the left (or right, if the left-adjustment flag has been given). Instead of a decimal digit string one may write
"*"
or"*m$"
(for some decimal integer m) to specify that the field width is given in the next argument, or in the m-th argument, respectively, which must be of type int. A negative field width is taken as a'-'
flag followed by a positive field width. In no case does a nonexistent or small field width cause truncation of a field; if the result of a conversion is wider than the field width, the field is expanded to contain the conversion result.
Post a Comment for "Formatted Strings For Rounding In Python"