JD. - 3 months ago 19

C# Question

I am given a floating number such as 1.77720212936401 and I want to be able to calculate roughly what the aspect ratio is as a width:height string with width and height being small natural numbers.

JD

///

I have come up with this, currently testing to see if it covers all areas:

`static public string Ratio(float f)`

{

bool carryon = true;

int index = 0;

double roundedUpValue = 0;

while (carryon)

{

index++;

float upper = index*f;

roundedUpValue = Math.Ceiling(upper);

if (roundedUpValue - upper <= (double) 0.1)

{

carryon = false;

}

}

return roundedUpValue + ":" + index;

}

Answer Source

Try multiplying it by small integers in a loop and check if the result is close to an integer.

```
double ar = 1.7777773452;
for (int n = 1; n < 20; ++n) {
int m = (int)(ar * n + 0.5); // Mathematical rounding
if (fabs(ar - (double)m/n) < 0.01) { /* The ratio is m:n */ }
}
```