Reputation: 146
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
Upvotes: 0
Views: 502
Reputation: 533
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.
Upvotes: 0
Reputation: 44831
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);
Upvotes: 1
Reputation: 54584
There is a minimum function you could use:
max = Math.min(x*0.8,800);
Upvotes: 1
Reputation: 20159
How about Math.min
?
x = 20000;
min = Math.min(x*0.08, 800);
value = x + min;
Upvotes: 4