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.
python3
>>> a = 1
>>> b = 6
>>> a / b
0.16666666666666666
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
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
[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