Search code examples
c#variablesmathcalc

Translate int value 100 to 0 and 0 to 100


I would like to find a good way how I can best translate an integer value. I have a method TranslateValue in which comes a value 100. now the weird part of the number hundred is to increment the who from 0 to 100 and if the value that comes in the method is for example 0 then the value is 100 which the method returns. So in short I want to have a counter method that calculates the other way around I have failed many times but I can't find a good way that works

    int currentValue = 0;

    private int TranslateValue(int valueToTranslate)
    {
        if (valueToTranslate > 0)
        {
            currentValue++;
        }
        else
        {
            currentValue--;
        }
    }

Solution

  • To map a value from 0 to 100 to the inverse range 100..0, simply

    return 100 - value;
    

    You may wish to add suitable checks around that, or just clamp the output to 0..100 with

    return Math.Min(100, Math.Max(0, 100 - value));