ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

Map

Re-maps a number from one range to another. That is, a value of fromLow would get mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-between, etc. (like Arduino function map) Parameters value: the number to map. fromLow: the lower bound of the value’s current range. fromHigh: the upper bound of the value’s current range. toLow: the lower bound of the value’s target range. toHigh: the upper bound of the value’s target range.

Source

public static class ExtensionMethods
{
    public static int Map(this int value, int fromLow, int fromHigh, int toLow, int toHigh)
    {
        return (value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow;
    }

    public static decimal Map(this decimal value, decimal fromLow, decimal fromHigh, decimal toLow, decimal toHigh)
    {
        return (value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow;
    }
}

Example

int sensorValue = 512;
int val = sensorValue.Map(0, 1023, 0, 100); // 50

Author: Jarod Weiss

Submitted on: 7 nov 2019

Language: csharp

Type: System.Int32

Views: 6280