How to round to 2 decimals with Python? How to round to 2 decimals with Python? python python

How to round to 2 decimals with Python?


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))


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


Most answers suggested round or format. round sometimes rounds up, and in my case I needed the value of my variable to be rounded down 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 up to a certain decimal place?

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

or:

from math import floor, ceildef roundDown(n, d=8):    d = int('1' + ('0' * d))    return floor(n * d) / ddef roundUp(n, d=8):    d = int('1' + ('0' * d))    return ceil(n * d) / d


matomo