Custom Search

PYTHON: Rounding numbers

The round() function is quite simple to use.

syntax: round(number, digits)

It returns a floating point number that is a rounded version of the number you put in the bracket, quoted to the number of decimal places you have given as digits.

The default number of decimals is 0, meaning that the function will return the nearest integer.

For example:

x = round(6.79743)

print(x)

Would return 7

x = round(16.72452,2)

print(x)

Would return 16.72

But....

x = round(16.79743,2)

print(x)

Would return 16.8

You will notice it does not give the zero required to be given for a two decimal place presentation.

How can we solve this?

Suppose you want to round off a float number to 2 decimal places or any other number of decimal places.

To do this you can use format specifiers .2f, .3f, or .nf for n decimal places.

 

For example - let's find π to 2 decimal places

num = 3.141592653589793

# Method 1:

print("num round to 2 decimal is {:.2f}".format(num))

# Method 2:

print(f"num round to 2 decimal is {num:.2f}")

Here is a program that I wrote to calculate and compare the overall value of resistors arranged in series and parallel.

It gives the parallel resistor value to 2 decimal places.

resistor1=input("What is the value of resistor 1 in ohms? ")
R1=int(resistor1)
resistor2=input("What is the value of resistor 2 in ohms? ")
R2=int(resistor2)
Rs=R1+R2
Rp = R1*R2/(R1+R2)
print("****************************************")
print("The value of a series combination of your two resistors would be ",Rs," ohms")
print(f"The value of a parallel combination of your two resistors would be {Rp:.2f} ohms")

You can play around with the code and make it give answers to a different number of places.