Question

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

Was it helpful?

Solution

How about Math.min?

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

OTHER TIPS

There is a minimum function you could use:

max = Math.min(x*0.8,800);

Modulus arithmetic isn't necessary or helpful here. Just use min:

x=20000; //can be 1000 to 20000
value = x + Math.min(x*0.8, 800);

You want to use Math.min(), I think...

function getNewValue(iInput) {
    var modifier = 0.08;
    var max = 800;
    return iInput + (Math.min((iInput * modifier), max));
}

That way, you get the lesser of the two.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top