1

I want to round a integer using formatted strings, but it has to be via a parameter asked. I have the following code where p is the amount of decimals to be rounded to.

def fahrenheit_to_celsius(t, p):
    celsius = ((t - 32.0) * 5.0 / 9.0)

    print "%f "%(celsius)

3 Answers 3

4
def fahrenheit_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"
Sign up to request clarification or add additional context in comments.

1 Comment

Here is the documentation for the format string method.
1

In the format specifier, add .* between % and f. '.' specifying decimals, '*' specifying width to be picked from argument list.

def fahrenheit_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.

Comments

0
>>> def f_to_c(t, p=0):
...     return round(((t - 32.0) * 5.0 / 9.0), p)
... 
>>> print("{}".format(f_to_c(10, 2)))
-12.22

1 Comment

"{0}".format(round(1, 2)) prints "1.0" and not "1.00" as awaited…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.