How to round to 2 decimal with Python?

I get a lot of decimal places 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 a program around each answer up to the 2nd decimal place?

+127
python rounding
Dec 08 '13 at 18:13
source share
13 answers

You can use the round function, which takes a number as the first argument, and the second argument is precision.

In your case, it will be:

 answer = str(round(answer, 2)) 
+228
Dec 08 '13 at 18:20
source share
β€” -

Using str.format() syntax to display a answer with two decimal places (without changing the base value of the answer ):

 def printC(answer): print "\nYour Celsius value is {:0.2f}ΒΊC.\n".format(answer) 

Where:

  • : introduces specification
  • 0 allows signed zero padding for numeric types
  • .2 sets precision to 2
  • f displays the number as a fixed point number
+51
Dec 08 '13 at 18:35
source share

Most answers are suggested round or format . round sometimes rounded, and in my case, I need the value of my variable to be rounded, and not just displayed as such.

 round(2.357, 2) # -> 2.36 

I found the answer here: How do I round a floating point number to a specific decimal place?

 import math v = 2.357 print(math.ceil(v*100)/100) # -> 2.36 print(math.floor(v*100)/100) # -> 2.35 

or:

 from math import floor, ceil def roundDown(n, d=8): d = int('1' + ('0' * d)) return floor(n * d) / d def roundUp(n, d=8): d = int('1' + ('0' * d)) return ceil(n * d) / d 
+38
Apr 21 '17 at 3:43 on
source share
 float(str(round(answer, 2))) float(str(round(0.0556781255, 2))) 
+10
Mar 14 '17 at 1:32
source share

Just use formatting with% .2f, which gives a rounding to 2 decimal places.

 def printC(answer): print "\nYour Celsius value is %.2f C.\n" % answer 
+5
Dec 08 '13 at 18:18
source share

You can use the string formatting operator for python "%". "% .2f" means 2 digits after the decimal point.

 def typeHere(): 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(Fahrenheit): Celsius = (Fahrenheit - 32.0) * 5.0/9.0 return Celsius def printC(answer): print "\nYour Celsius value is %.2f C.\n" % answer def main(): printC(formeln(typeHere())) main() 

http://docs.python.org/2/library/stdtypes.html#string-formatting

+3
Dec 08 '13 at 18:16
source share

You want to round your answer.

round(value,significantDigit) is the usual solution for this, however, this sometimes does not work, as one might expect from a mathematical point of view, when the digit is immediately inferior (to the left of) to the digit, re rounding to has a value of 5 .

Here are some examples of this unpredictable behavior:

 >>> round(1.0005,3) 1.0 >>> round(2.0005,3) 2.001 >>> round(3.0005,3) 3.001 >>> round(4.0005,3) 4.0 >>> round(1.005,2) 1.0 >>> round(5.005,2) 5.0 >>> round(6.005,2) 6.0 >>> round(7.005,2) 7.0 >>> round(3.005,2) 3.0 >>> round(8.005,2) 8.01 

Assuming you intend to do the traditional rounding of statistics in the sciences, this is a convenient wrapper to get the round function, which works as expected, in import additional things like Decimal .

 >>> round(0.075,2) 0.07 >>> round(0.075+10**(-2*6),2) 0.08 

Yeah! Therefore, based on this, we can make a function ...

 def roundTraditional(val,digits): return round(val+10**(-len(str(val))-1)) 

This basically adds a very small value to the string to force it to be rounded up in unpredictable instances where there is usually no round function when you expect it. The convenient value to add is 1e-X , where X is the length of the line you are trying to use round in plus 1 .

The use approach of 10**(-len(val)-1) was intentional, as this is the largest small number you can add to force a shift, while also ensuring that the value you add never changes the rounding, even if there is no decimal . . I could only use 10**(-len(val)) with condiditional if (val>1) to subtract 1 more ... but it's easier to just subtract 1 , as that will not change much of the applicable decimal range, which is a workaround The solution can handle correctly. This approach will not succeed, if your values ​​reach the limits of the type, it will not succeed, but for an almost complete range of valid decimal values ​​it should work.

Thus, the finished code will look something like this:

 def main(): printC(formeln(typeHere())) def roundTraditional(val,digits): return round(val+10**(-len(str(val))-1)) 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(roundTraditional(answer,2)) print "\nYour Celsius value is " + answer + " C.\n" main() 

... should give you the expected results.

You can also use the decimal library, but the shell that I suggest is simpler and may be preferred in some cases.




Edit: Thanks to Blckknght for the fact that case 5 only occurs for certain values.

+2
Jul 07 '16 at 7:18
source share

You can use the round function.

 round(80.23456, 3) 

will give you an answer of 80.234

In your case use

 answer = str(round(answer, 2)) 

Hope this helps :)

+1
Jun 30 '16 at 5:56
source share

Here is an example that I used:

 def volume(self): return round(pi * self.radius ** 2 * self.height, 2) def surface_area(self): return round((2 * pi * self.radius * self.height) + (2 * pi * self.radius ** 2), 2) 
+1
Nov 23 '17 at 4:42 on
source share

I don’t know why, but the format is {: 0.2f} '. (0.5357706) gives me 0.54. The only solution that works for me (Python 3.6) is this:

 def ceil_floor(x): import math return math.ceil(x) if x < 0 else math.floor(x) def round_n_digits(x, n): import math return ceil_floor(x * math.pow(10, n)) / math.pow(10, n) round_n_digits(-0.5357706, 2) -> -0.53 round_n_digits(0.5357706, 2) -> 0.53 
+1
Apr 02 '18 at 2:21
source share

You can use the rounding operator to 2 decimal

 num = round(343.5544, 2) print(num) // output is 343.55 
+1
Feb 06 '19 at 6:27
source share

How do you want your answer to be decimal, so you do not need to output the response variable to a string in the printC () function.

and then use printf-style String Formatting

0
Dec 08 '13 at 18:37
source share
 round(12.3956 - 0.005, 2) # minus 0.005, then round. 

Reply from: stack overflow

0
May 23 '18 at 7:34
source share



All Articles