Method for calculating the percentage for a value between two boundaries

I have the following calculation:

float value = MY_VALUE;

float percentage = (value - MIN)/(MAX - MIN);
if (percentage < 0)
   percentage = 0;
if (percentage > 1)
   percentage = 1

I'm just wondering if there is any method that exists in Objective-C or C to help accomplish this, for example, a method that will span “float” values, between the MIN and MAX bounds.

+3
source share
4 answers

No.

In another note, you should probably update your code to prevent possible division by zero:

float den = (value - MIN);
float num = (MAX - MIN);
float percentage;

if(den) {
  percentage = num / den;
  if (percentage < 0.0f ) {
    percentage = 0.0f;
  } else if (percentage > 1.0f) {
    percentage = 1.0f;
  } else {
    printf("Percentage: %3.2f",percentage);
  }
} else {
  percentage = 0.0f;
  printf("DIVIDE BY ZERO ERROR!");
}

Also, be careful. Oracle is suing Google for very similar code. You might want to review the publication publicly:

http://developers.slashdot.org/story/12/05/16/1612228/judge-to-oracle-a-high-schooler-could-write-rangecheck

+1
source

C ( Objective C).

+3

objective-c, .

(I think Soberd was wrong (opposite) in line 6). This is what I did, and it works the way I wanted.

- (CGFloat)calculateProgressForValue:(CGFloat)value start:(CGFloat)start end:(CGFloat)end
{    
    CGFloat diff = (value - start);
    CGFloat scope = (end - start);
    CGFloat progress;

    if(diff != 0.0) {
        progress = diff / scope;
    } else {
        progress = 0.0f;
    }

    return progress;
}

And you can always limit this so as not to go from 0.0 or 1.0 like this:

- (CGFloat)progressConstrained {

    // example values
    CGFloat start = 80;
    CGFloat end = 160;
    CGFloat a = 100;

    // the constrain
    return MAX(0.0, MIN(1.0, [self calculateProgressForValue:a start:start end:end]))
}
+1
source

If you just want to make sure that the value is not higher or lower than other values, you should use MAX (a, b) and MIN (a, b) ...

float maxValue = 1.0;
float minValue = 0.0;
float myValue = 2.8;
float myValueConstrained = MAX(minValue, MIN(maxValue, myValue)); // 1.0

MIN (a, b) takes the smallest of a and b

MAX (a, b) takes the largest of a and b


Usually I just do this:

float myValueConstrained = MAX(0.0, MIN(1.0, myValue));
+1
source

All Articles