Skip to content

Instantly share code, notes, and snippets.

@illtellyoulater
Forked from fpillet/scale.js
Last active January 26, 2023 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save illtellyoulater/16a0ce919abe3c60277698e9138a620e to your computer and use it in GitHub Desktop.
Save illtellyoulater/16a0ce919abe3c60277698e9138a620e to your computer and use it in GitHub Desktop.
Javascript value scaling between two ranges, the correct way
function convertRange( value, r1, r2 ) {
return ( value - r1[ 0 ] ) * ( r2[ 1 ] - r2[ 0 ] ) / ( r1[ 1 ] - r1[ 0 ] ) + r2[ 0 ];
}
// example
convertRange(26, [0, 100], [-2, 2]);
// = -0.96
// another example
convertRange(26, [0, 100.1], [-2, 2]);
// = -0.9610389610389609
// Originally found it on https://stackoverflow.com/a/14224813/988591 (thanks Oleq!)
// It seems to work perfectly.
// The problem with the originally forked function was that it worked with integers only
// making it very imprecise when dealing with small numbers, for example:
scaleValue(26, [0, 100], [-2, 2]);
// would just return 0
// The solution in this gist uses linear interpolation, which is essential in so many situations,
// but for some reason I keep forgetting and rediscovering it every 5 years or so...
// Hopefully this time it will stick... ;)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment