Reputation: 14443
Example:
I'm trying to figure out the calculation for finding the percentage between two values that a third value is.
Example: The range is -46 to 195. The value -46 would 0%, and the value 195 would be 100% of the range. What percentage of this range is the value 65?
valueMin=-46
valueMax=195
valueNow=65
valuePercentage = ?
I have tried the following algorithm but it doesn't work :
const log = (txt) => console.log(txt, 'instead of 100%');
function getValueNowInPercent(valueMin, valueMax, valueNow){
const diff = valueMax - valueMin;
const percent = valueNow / diff * 100;
return percent + '%';
}
let valueMin, valueMax, valueNow;
valueMin = 0; valueNow = 50; valueMax = 100;
log(getValueNowInPercent(valueMin,valueNow,valueMax));
==> 200% instead of 100%
valueMin = -100; valueNow = 0; valueMax = 100;
log(getValueNowInPercent(valueMin,valueNow,valueMax));
==> 100% instead of 100%
valueMin = 0; valueNow = 100; valueMax = 200;
log(getValueNowInPercent(valueMin,valueNow,valueMax));
==> 200% instead of 100%
valueMin = -200; valueNow = 0; valueMax = 200;
log(getValueNowInPercent(valueMin,valueNow,valueMax));
==> 100% instead of 100%
Upvotes: 3
Views: 2328
Reputation: 4876
How about mapping this into domain range problem where domain would be your min and max values and range will be from 0 to 100
function mapBetween(currentNum, minAllowed, maxAllowed, min, max) {
return (maxAllowed - minAllowed) * (currentNum- min) / (max - min) + minAllowed;
}
console.log (mapBetween(-46,0,100,-46,195))
console.log (mapBetween(195,0,100,-46,195))
console.log (mapBetween(65,0,100,-46,195))
console.log (mapBetween(100,0,100,0,200))
Upvotes: 10