2

Does anyone know how to round a number to nearest .0125? For example there's a number 167.1131 then it needs to be converted to 167.1125. I have tried to do it with round but it rounds to 0.x.

Michael
  • 109
  • 1
  • 1
  • 13
  • Possible duplicate of [Round up to Third decimal Place in Python](https://stackoverflow.com/questions/9232256/round-up-to-third-decimal-place-in-python) – quamrana Feb 06 '18 at 08:54
  • 1
    What is the end purpose of the rounding up? This issue, perhaps can be addressed elsewhere along the line? – Sazzy Feb 06 '18 at 09:06

3 Answers3

9

Convert it to "0.0125's", round THAT, and convert back:

round(x/0.0125)*0.0125
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • Hmm, other way round? – quamrana Feb 06 '18 at 08:54
  • @quamrana: Well, if x=5, the above yields 5, while switching the '*' and '`' (which is what I assume "other way round" means) yields 0. So, no? – Scott Hunter Feb 06 '18 at 12:25
  • Ok, my bad. I usually mistake true for false in `if` statements. This time its mistaking `/0.0125` for `/80`! I would do it like this: `round(x*80)/80` – quamrana Feb 06 '18 at 12:32
  • @quamrana: Or there's also `0.125 * round(x*8.0, 1)`, which should be correctly rounded (in case that matters, and assuming that overflow and underflow are avoided in the multiplications). – Mark Dickinson Feb 06 '18 at 12:54
2

The round() function is focused on rounding to tenths, hundredths, thousandths and so on - essentially rounding to some negative exponent of 10.

So, as 0.0125 is not such a number that the round() can handle, you can

  • either apply a multiplication to your input number before giving it to round, so that it can do a rounding for which it is designed, and afterwards you correct for the initial multiplication. One of the other answers does it like this.
  • or you can, if you think the first approach looks complicated, solve the problem with pure mathematics. The code below essentially looks how much there is actually "too much" above a multiple of 0.0125. This "too much" amount is a remainder (modulus) of a division. This division is done on integers, so there is an initial multiplication and correction afterwards, just like in the first approach.

Code for the second approach:

def round_0125(number):
    mult_number = number * 10000
    remainder = mult_number % 125
    return (mult_number - remainder) / 10000

round_0125(167.1131)
#167.1125

round_0125(167.5738)
#167.5625
Sander Vanden Hautte
  • 2,138
  • 3
  • 22
  • 36
0
value = 167.1125
dec_value = value % 1     # get decimal part
whole_value = value // 1
my_range = np.arange(0, 1, 0.0125)

distance = np.abs(dec_value - my_range)   # get the absolute distance
index = np.argmin(distance)   # find the index of smallest distance
result = whole_value + my_range[index]
hamster ham
  • 729
  • 8
  • 8