Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scaling between two number ranges

Tags:

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;
like image 631
alyx Avatar asked Jan 08 '13 21:01

alyx


2 Answers

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
like image 163
oleq Avatar answered Oct 15 '22 16:10

oleq


Use percentages:

xMax = 10;
xMin = 1;

yMax = 559.22;
yMin = 300.77;

percent = (inputY - yMin) / (yMax - yMin);
outputX = percent * (xMax - xMin) + xMin;
like image 31
Foggzie Avatar answered Oct 15 '22 16:10

Foggzie