I’m trying to write a function to return a certain value if the input is between a certain number range.
Normally, I would just write a series of if/else if statements to do the job. But, I’m working with a large number of ranges so writing out 30+ if/else if statements seems inefficient.
Let’s say I have a set min and max number for the overall range and I want to break that up into smaller ranges. For each range, I want to return some value. Ideally, the return value for each range will decrease by some set number.
For context, I’m trying to use something similar to this to calculate a value based on mileage. For example, if the mileage is between 101-120 miles, the rate is equal to 80% of the mileage. As the mileage increases, the percentage decreases. And, the number that the percentage decreases by can be some set number (-0.05
for example)
...
else if (m >= 101 && m <= 120) return 0.80
else if (m >= 121 && m <= 140) return 0.75
...
Since there is a pattern to the return values for each range, I’m thinking this can be done in a better way than just writing out a bunch of if/else statements but I’m not sure exactly how that can be done. Any ideas?
2
Answers
Your example doesnt increment by 15; so, I’m assuming that was a typo.
The solution I would use is a function.
ie.
something like that ?