How to round to two decimals in Python?

How to round to two decimals in Python?

Hey Keerti,

You can use the round function, which takes the number as its first argument and the precision after the decimal point as its second argument.

For your case, it would be:

answer = str(round(answer, 2))

Hello Keerti,

The given answer by @Richaa Roy changes the value of answer. If you simply want to round for display purposes without altering the underlying value, use the solution below.

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

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

Where:

  • : introduces the format specification
  • 0 enables sign-aware zero-padding for numeric types
  • .2 sets the precision to 2 decimal places
  • f displays the number as a fixed-point number

Hey Keerti,

If you need to avoid floating-point issues when rounding numbers for accounting purposes, you can use numpy’s round function.

First, you need to install numpy:

pip install numpy

Then, use the following code:

import numpy as np

print(round(2.675, 2))
print(float(np.round(2.675, 2)))

This will print:

2.67
2.68

You should use numpy rounding if you are managing money with legal rounding requirements.