-
-
Save illtellyoulater/16a0ce919abe3c60277698e9138a620e to your computer and use it in GitHub Desktop.
Javascript value scaling between two ranges, the correct way
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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