3

I have a float. I want to round it to the nearest multiple of n, where n is any float. How can I do this?

In my particular instance, I need my float to be a multiple of 0.96f, but 0.96f is subject to change.

For example, if I have 1.0f, I want to get 0.96f. Or if I have 1.75f, I want to get 1.92f. I do not need to account for negative numbers, although it would be good if it did.

I have checked the other questions about rounding, but they are all in powers of 2. (0.25, 0.5, 1, 2, etc.)

Evorlor
  • 7,263
  • 17
  • 70
  • 141
  • can you provide examples so we are clear on your requirements? – user1666620 Oct 05 '16 at 14:20
  • 3
    In general, use `ROUND(x/n)*n` – D Stanley Oct 05 '16 at 14:22
  • I marked a duplicate that's in Java, but the premise is the same. Note also that you can use whichever of the various rounding options (`AwayFromZero`, `ToEven`) are appropriate. – D Stanley Oct 05 '16 at 14:27
  • For `float` you just need type casting https://stackoverflow.com/questions/2705542/returning-the-nearest-multiple-value-of-a-number/47176199#47176199 – Xpleria Nov 08 '17 at 09:45

1 Answers1

8

Divide your input (n) by the number you're rounding to (x), round that, and multiply that back with x and that's your result!

double RoundToNearest(double n, double x) {
    return round(n / x) * x;
} 
Trevor Wilson
  • 193
  • 2
  • 7