I am creating a function that rounds a view frame's CGFloat to its nearest discrete value based on a custom variable granularity.
For example, if my granularity (multiplier) was 0.25, I am trying to create a function that takes an input of 0.3 and returns 0.25, or 3.89 and returns 4.00 (closes multiple of 0.25). As of now, I've found several posts on how to round to the nearest decimal, but they don't seem to apply in this case.
let x = 1.23556789
let y = Double(round(1000*x)/1000)
print(y) //This removes all decimals but three, but only seem to work with multiples of 10.
Any idea on how I could go about doing this?
Thanks!
You can use the same approach as rounding to a power of 10 here.
When you want to round to the nearest 0.1, you multiply by 10, round, then divide by 10. When you want to round to the nearest 0.01, you multiply by 100, round, then divide by 100.
See the pattern here? The number you multiply and divide by is always 1 over the granularity!
So for the granularity of 0.25, you multiply and divide by 4:
print(round(0.3 * 4) / 4)
// or
print(round(0.3 / 0.25) * 0.25)
More generally, given a granularity: Double and a number to round x: Double, we can round it like this:
let rounded = round(x / granularity) * granularity
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With