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:
Would return 7
Would return 16.72 But....
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:
# Method 2:
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.
You can play around with the code and make it give answers to a different number of places. |
|