Grant - 2 years ago 109
Swift Question

# How do you round a variable to the nearest number in an array in swift?

I have a block of code in swift in which the final calculation needs to be rounded to the nearest number in a pre-defined array? How would you do that?

``````var array = [8, 23, 31, 46, 54, 69, 77, 92, 100, 115, 123, 138]
var finalCalculation = 55.5
//round 55.5 to the nearest number in array which is 54
``````

The only way I could think up was to loop through and keep track of which one was closest and compare that to the next item in the array, however, I'm sure this could be improved upon, here:

``````var array: Array<Double> = [8, 23, 31, 46, 54, 69, 77, 92, 100, 115, 123, 138]
var finalCalculation: Double = 55.5

var closest: Double = array[0]

for item in array {
if abs(finalCalculation - item) < abs(finalCalculation - closest) {
closest = item
}
}

print(closest)
``````

The abs part is to ensure that you're getting the distance between the numbers.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download