Search code examples
javascriptmathpercentagealgebra

math - add percentage at value, but limit to a max?


I'm making a function that will add percentage of a value up to a max of over "percentage-value"

I will try to explain

5000units * 0,08 = 400
10000units * 0,08 = 800
20000units * 0,08 = 1600 <-I want this to be 800, because thats my max.

I can solve it by using IFs

x=20000; //can be 1000 to 20000
if(x*0,08>800){
 max=800;
}
else{
 max=x*0,08;
}
value=x+max;

But is there a way of doing this by pure math? maybe using modulus?

Best regards Niclas


Solution

  • How about Math.min?

    x = 20000;
    min = Math.min(x*0.08, 800);
    value = x + min;