1

I have an animation timeline of sorts that has a resolution set which is a factor of 1 second.

A resolution of 4 is (1000/4) which means that events are called every .25 .5 and .75th of a second.

I need a way to round the decimals of floats that the user enters to the set resolution so that my timeline events can only start and end on numbers from the resolution.

With a resolution of 4, 1.20 would round up to 1.25, 4.85 would be rounded down to 4.75, and 2.5 wouldn't be rounded

What is the simplest way to do this using the given the float in question and the resolution?

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Keith M
  • 1,199
  • 2
  • 18
  • 38
  • http://stackoverflow.com/questions/1329426/how-do-i-round-to-the-nearest-0-5 or http://stackoverflow.com/questions/2826262/round-a-decimal-to-the-nearest-quarter-in-c-sharp – Marc Mar 29 '16 at 18:44

1 Answers1

1

Just scale your values by your "resolution", round to nearest integer, then scale it back, like this:

double originalValue = 1.2;
double resolution = 4;
double roundedValue;

roundedValue = Math.Round(originalValue * resolution, MidpointRounding.AwayFromZero) / resolution; // 1.25

The MidpointRounding.AwayFromZero option is needed to get *.5 rounded "up" (i.e. away from zero).

SlimsGhost
  • 2,849
  • 1
  • 10
  • 16
  • You may want to use `Math.Round(originalValue * resolution, MidpointRounding.AwayFromZero)` as the default is `MidpointRounding.ToEven`. – Andrew Morton Mar 29 '16 at 18:47