user14343924
user14343924

Reputation:

Percentage value from different ranges

I tried from yesterday to find a formula in JavaScript (also math formula) that return the value, of a given percentage from 3 different cases.

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 ?

Upvotes: 1

Views: 408

Answers (1)

Noa
Noa

Reputation: 1216

Here is your formula: Try this.

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));

Upvotes: 2

Related Questions