# 将不同长度的数字舍入到最接近的 0 或 5

[英]Round numbers of different lengths to nearest 0 or 5

``````1291 -> 1290
0.069 -> 0.07
1.08 -> 1.1
14 -> 15
6 -> 5
``````

``````import numpy as np
convDict = {
"0":"0",
"1":"0",
"2":"0",
"3":"5",
"4":"5",
"5":"5",
"6":"5",
"7":"5",
"8":"0",
"9":"0"
}

def conv(f):
str_f = str(f)

# if input is like, 12. or 13.0,so actually int but float data type
# We will get rid of the .0 part
if str_f.endswith(".0"):
str_f = str(int(f))

# We need last character, and other body part
last_f = str_f[-1]
body_f = str_f[:-1]

# if last char is 8 or 9 we should increment body last value
if last_f in "89":
# Number of decimals
numsOfDec = body_f[::-1].find('.')

# numsOfDec = -1 means body is integer, we will add 1
if numsOfDec == -1:
body_f = str(int(body_f) + 1)

else:
# We will add 10 ** -numsOfDec , but it can lead some numerical differences like 0.69999, so i rounded
body_f = str(np.round(float(body_f) + 10 ** (-numsOfDec),numsOfDec))

# Finally we round last char
last_f = convDict[last_f]
return float(body_f + last_f)
``````

``````print(conv(1291))
print(conv(0.069))
print(conv(1.08))
print(conv(14))
print(conv(6))
print(conv(12.121213))
print(conv(12.3))
print(conv(18.))
print(conv(18))
``````

`````` i = decimal.Decimal('0.069')
i.as_tuple().exponent
-3
``````

``````round(0.069/5, 3) * 5
``````

`````` if number % 1 == 0:
return round(int(number)/5)*5
else:
index = decimal.Decimal(str(number)).as_tuple().exponent
return round(number/5, -index)*5
``````

``````import math
import decimal

def round_half_up(n):
if (str(n).find(".") > 0):
decimalsource = len(str(n).split(".")[1])
base = 10**decimalsource
number = n*base
rounded = 5 * round(number/5)
result = rounded / base
if (result == int(result)):
return int(result)
else:
return result
else:
return 5 * round(n/5)

print(round_half_up(1291))
print(round_half_up(0.069))
print(round_half_up(1.08))
print(round_half_up(14))
print(round_half_up(6))
print(round_half_up(12.121213))
print(round_half_up(12.3))
print(round_half_up(18.))
print(round_half_up(18))
``````

[英]How to round numbers to the nearest 1000?

2017-09-29 03:24:52 2 5886   rounding

[英]choose numbers of different lengths

2013-05-12 13:05:47 3 39   slice

[英]Matching nearest values in two dataframes of different lengths

[英]Searching numbers in line with different lengths

2020-09-25 15:56:56 2 24   line

[英]Combining 2 dataframes of different lengths by nearest observed datetime index

[英]Round in numpy to Nearest Step

2011-10-22 11:23:41 3 11109   rounding

[英]Round number to nearest integer

2015-08-04 19:51:39 16 598741   python

[英]Round up to the nearest 0.05

Python舍入到最接近的.0125

[英]Python round to nearest .0125