Scaling between two number ranges

alyx picture alyx · Jan 8, 2013 · Viewed 21.6k times · Source

I remember using an equation to do this at some point – how do you do this in Javascript?

Plugin two number ranges:

rangeX = 1 (through) 10;
rangeY = 300.77 (through) 559.22;

Input a value in the rangeY scale:

inputY = 328.17;

Convert to proportional value in rangeX scale:

outputX = 1.43;

Answer

oleq picture oleq · Jan 8, 2013
function convertRange( value, r1, r2 ) { 
    return ( value - r1[ 0 ] ) * ( r2[ 1 ] - r2[ 0 ] ) / ( r1[ 1 ] - r1[ 0 ] ) + r2[ 0 ];
}

convertRange( 328.17, [ 300.77, 559.22 ], [ 1, 10 ] );

>>> 1.9541497388276272