首页 > 解决方案 > 不同范围的百分比值

问题描述

我从昨天开始尝试在 JavaScript 中找到一个公式(也是数学公式),它返回来自 3 个不同案例的给定百分比的值。

Example:
range A = [0, 10 ] - percentage 25% => value will be 2.5
range B = [0, 100] - percentage 50% => value will be 50

but how do I treat this 2 cases?:

case 1 = range [-5, 5  ] - percentage for example 50% => value will be 0
case 2 = range [-10, 0 ] - percentage for example 25% => value will be -7.5
case 3 = range [-11, -1] - percentage for example 30% => value will be ?

标签: javascriptmathpercentage

解决方案


这是你的公式:试试这个。

const percentage = function(x, y, perc){
    // x is start point
    // y is end point
    // so you need length of this range (between x and y) and we subtract x from y
    // and dividing to 100 (because 100% is full range between x and y)
    // when we divide it to 100, the result is 1% of the range
    // then we multiply it to percentage we want for example 25%
    // and adding x to result. Because we started from x;



    return ((y-x)/100)*perc+x;
}

console.log(percentage(0,10,25));
console.log(percentage(0,100,50));
console.log(percentage(-5,5,50));
console.log(percentage(-10,0,25));
console.log(percentage(-11,-1,30));


推荐阅读