Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round a number based on a ratio in C#

Tags:

c#

math

rounding

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?

like image 401
user1423893 Avatar asked Nov 10 '22 14:11

user1423893


1 Answers

Math.Pow(factor, Math.Floor(Math.Log(ratio, factor)))
like image 162
Rik Avatar answered Nov 14 '22 21:11

Rik