You can use the round function, which takes as its first argument the number and the second argument is the precision after the decimal point.
In your case, it would be:
answer = str(round(answer, 2))
Answer from rolisz on Stack OverflowYou can use the round function, which takes as its first argument the number and the second argument is the precision after the decimal point.
In your case, it would be:
answer = str(round(answer, 2))
Using str.format()'s syntax to display answer with two decimal places (without altering the underlying value of answer):
def printC(answer):
print("\nYour Celsius value is {:0.2f}ºC.\n".format(answer))
Where:
:introduces the format spec0enables sign-aware zero-padding for numeric types.2sets the precision to2fdisplays the number as a fixed-point number
How to round a whole number to 2 decimal places
how to limit or round a float to only two decimals without rounding up
How do I represent currency (i.e., rounding to two decimal places) in Python? I just started learning a few days ago, and any explanation I've found of the decimal function is overwhelming at this point. ELI5, plz?
You're thinking about the wrong aspect of the problem. Yes, floating point innaccuracies mean you get a number like 30.00000000000000001, and decimal will fix that - but you can still divide a price and get a value like $3.718. Decimal won't help you there.
What you really want is a way to round the value to 2 decimal places when you print it. That's the only time that it matters, unless you're a bank and you really care about tiny fractions of a cent (in which case you'll use decimal as well as the following advice).
Check out the format function.
price=14.6188
print("The price is: ${:.2f}".format(price))
The price is: $14.62This function is very powerful and you should get familiar with it.
product="beer"
print("The price of {:} is ${:.2f}".format(product, price))
The price of beer is $14.62 More on reddit.com How to use the float() command to create 2 decimal places instead of one in a product of 2 numbers [the product is dollar amount]
Videos
When I print for example 56 I want it to print 56.00. How can I do this?