Easy way to round off to the nearest whole number with python3

How to calculate by rounding at the decimal point position specified by python3

I'll forget it soon, so I'll write it down as a reminder. ** There is round () ** Rounding after the decimal point is easy, but I didn't know.

The default is

python3


>>> a = 1
>>> b = 6
>>> a / b
0.16666666666666666

Use the round function

python3


>>> round((a / b), 1)
0.2
>>> round((a / b), 2)
0.17
>>> round((a / b), 3)
0.167
>>> round((a / b), 4)
0.1667

Postscript

There was a lack of consideration, so I will add it.

In python3 series, it was sometimes not rounded well due to rounding. Note because I was addicted to rounding python3 This person was also resolved. It was very helpful including explanations.

For example, it is like this that inconvenience occurs in just round.

python3


>>> round(1.1115, 3)
1.111
>>> round(1.1125, 3)
1.113

Including such cases, I think that it is possible to round off float types of arbitrary length with the following functions.

python3


def custom_round(number, ndigits=0):
    if type(number) == int:#If it is an integer, return it as it is
        return number
    d_point = len(str(number).split('.')[1])#Define how many digits are after the decimal point
    if ndigits >= d_point:#If the value after the decimal point is larger than the argument, return it as it is.
        return number
    c = (10 ** d_point) * 2
    #Value for doubling the number of digits after the decimal point by adding 0 to the original number to make it an integer(0.If 01, c is 200)
    return round((number * c + 1) / c, ndigits)
    #Add 0 to the original number to make an integer, double it, add 1 and divide by 2. The original number is 0.01 is 0.Set to 015 and round

Execution example


>>> round(1.1115, 3)
1.111
>>> round(1.1125, 3)
1.113
>>>
>>> custom_round(1.1115, 3)
1.112
>>> custom_round(1.1125, 3)
1.113
>>> round(4.5)
4
>>> round(3.5)
4
>>> custom_round(4.5)
5.0
>>> custom_round(3.5)
4.0

Reference link

[Python / Sample / Manipulation of values after the decimal point, rounding, rounding, and truncation](http://ll.just4fun.biz/?Python/%E3%82%B5%E3%83%B3%E3%83%97 % E3% 83% AB /% E5% B0% 8F% E6% 95% B0% E7% 82% B9% E4% BB% A5% E4% B8% 8B% E3% 81% AE% E5% 80% A4% E3% 81% AE% E6% 93% 8D% E4% BD% 9C% E3% 83% BB% E5% 9B% 9B% E6% 8D% A8% E4% BA% 94% E5% 85% A5% E3% 82% 84% E5% 88% 87% E4% B8% 8A% E3% 81% 92% E3% 80% 81% E5% 88% 87% E6% 8D% A8% E3% 81% A6) Honke (2. Built-in functions #round ()) Note because I was addicted to rounding python3

Recommended Posts

Easy way to round off to the nearest whole number with python3
An easy way to pad the number with zeros depending on the number of digits [Python]
The easiest way to synthesize speech with python
The easiest way to use OpenCV with python
Introduction to Python with Atom (on the way)
Easy way to check the source of Python modules
Easy way to scrape with python using Google Colab
Probably the easiest way to create a pdf with Python3
Easy way to customize Python import
An easy way to hit the Amazon Product API in Python
The fastest way to get camera images regularly with python opencv
[Python] Round up with just the operator
Easy way to use Wikipedia in Python
The road to compiling to Python 3 with Thrift
[Python] Easy introduction to machine learning with python (SVM)
The fastest way for beginners to master Python
The easiest way to get started with Django
Easy way to use Python 2.7 on Cent OS 6
Try to solve the man-machine chart with Python
Calculate the total number of combinations with python
Specify the Python executable to use with virtualenv
Say hello to the world with Python with IntelliJ
Excel X Python The fastest way to work
An easy way to call Java from Python
python beginners tried to predict the number of criminals
How to get the number of digits in Python
[Introduction to Python] How to iterate with the range function?
Try to solve the internship assignment problem with Python
The first algorithm to learn with Python: FizzBuzz problem
How to identify the element with the smallest number of characters in a Python list?
I tried to touch the CSV file with Python
I tried to solve the soma cube with python
[python] option to turn off the output of click.progressbar
[Python] How to specify the download location with youtube-dl
Convert the image in .zip to PDF with Python
An easy way to create an import module with jupyter
I want to inherit to the back with python dataclass
Make it easy to install the ROS2 development environment with pip install on Python venv
Specify MinGW as the compiler to use with Python
I tried to solve the problem with Python Vol.1
[Python] How to rewrite the table style with python-pptx [python-pptx]
How to count the number of occurrences of each element in the list in Python with weight
It is easy to execute SQL with Python and output the result in Excel
I tried to solve AOJ's number theory with Python
I tried to get the number of days of the month holidays (Saturdays, Sundays, and holidays) with python
How to know the number of GPUs from python ~ Notes on using multiprocessing with pytorch ~
An easy way to view the time taken in Python and a smarter way to improve it
I tried to find the entropy of the image with python
I tried to simulate how the infection spreads with Python
I tried to analyze the whole novel "Weathering with You" ☔️
I wanted to solve the Panasonic Programming Contest 2020 with Python
[python] Change the image file name to a serial number
The first API to make with python Djnago REST framework
Minimum knowledge to get started with the Python logging module
[Part.2] Crawling with Python! Click the web page to move!
What I did to welcome the Python2 EOL with confidence
[Python] I want to use the -h option with argparse
[Homology] Count the number of holes in data with Python
[Python] An easy way to visualize energy data interactively [plotly.express]
Try to automate the operation of network devices with Python
The usual way to add a Kernel with Jupyter Notebook