如何计算第三个值所在的两个值范围之间的百分比

时间:2017-02-08 10:33:15

标签: javascript math

示例:

我正在试图计算出找到第三个值的两个值之间的百分比的计算。

示例:范围是-46到195.值-46将为0%,值195将为范围的100%。这个范围的百分比是65?

valueMin = -46

valueMax = 195

valueNow = 65

valuePercentage =?

我尝试了以下algorithm,但它不起作用:

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%

1 个答案:

答案 0 :(得分:3)

如何将此映射到域范围问题,其中域将是您的最小值和最大值,范围将从0到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))