Question

I would like to round a number that is based on ratio of two values.

The ratio will include values that are greater or less than the original value where

ratio = newValue / originalvalue

When newValue > originalValue I can round to the nearest lower factor using:

double NearestLowerFactor(float value, double factor)
{
    return Math.Floor(value / factor) * factor;
}

For example:

  • factor = 2
  • ratio = 3
  • NearestLowerFactor = 2

When newValue < originalValue I wish to round to the nearest reciprocal of the factor.

Therefore, if the factor is 2 I would like to round based on factors of 1/2, that is 1/2, 1/4, 1/8, 1/16, etc.

For example:

  • originalValue = 8
  • newValue = 3
  • ratio = 0.375
  • NearestLowerFactor = 0.25 or 1 / 4.

How would I round to the closest lower factor in this case?

Was it helpful?

Solution

Math.Pow(factor, Math.Floor(Math.Log(ratio, factor)))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top