Home > Enterprise >  Round to the nearest number of a list
Round to the nearest number of a list

Time:05-01

I am writing a program that returns a value between 0 and 0.25. I want to round this value to the closest of a predefined list of values.

For example given a list of

round_to = [0,0.1,0.15,0.2,0.25]

A value of 0.004 should be rounded to 0, a value of 0.09 -> 0.1, a value of 0.126 -> 0.15, a value of 0.22 -> 0.2, and so on.

Does anyone know an elegant way to accomplish this?

Any insights are much appreciated!

CodePudding user response:

You can use min() with a key parameter that compares entries in round_to based on the absolute value of the difference between each value:

round_to = [0,0.1,0.15,0.2,0.25]
entry = 0.126

min(round_to, key=lambda x: abs(x - entry))

This outputs:

0.15
  • Related