Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round to 2 decimals with Python?

I am getting a lot of decimals in the output of this code (Fahrenheit to Celsius converter).

My code currently looks like this:

def main():     printC(formeln(typeHere()))  def typeHere():     global Fahrenheit     try:         Fahrenheit = int(raw_input("Hi! Enter Fahrenheit value, and get it in Celsius!\n"))     except ValueError:         print "\nYour insertion was not a digit!"         print "We've put your Fahrenheit value to 50!"         Fahrenheit = 50     return Fahrenheit  def formeln(c):     Celsius = (Fahrenheit - 32.00) * 5.00/9.00     return Celsius  def printC(answer):     answer = str(answer)     print "\nYour Celsius value is " + answer + " C.\n"    main() 

So my question is, how do I make the program round every answer to the 2nd decimal place?

like image 362
Dolcens Avatar asked Dec 08 '13 18:12

Dolcens


People also ask

How do you round decimals in Python?

Python round() Function The round() function returns a floating point number that is a rounded version of the specified number, with the specified number of decimals. The default number of decimals is 0, meaning that the function will return the nearest integer.


2 Answers

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)) 
like image 189
rolisz Avatar answered Sep 24 '22 12:09

rolisz


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 spec
  • 0 enables sign-aware zero-padding for numeric types
  • .2 sets the precision to 2
  • f displays the number as a fixed-point number
like image 25
Johnsyweb Avatar answered Sep 22 '22 12:09

Johnsyweb