I am trying to map all the Integers in the range [0.0, 100.0].
I know that the formula is:
((input - min) * 100) / (max - min)
You can imagine that if you want to map the entire Integer domain you will have to use Integer.MIN_VALUE and Integer.MAX_VALUE.
double percentage = ((double) input - Integer.MIN_VALUE) * 100 / (Integer.MAX_VALUE - Integer.MIN_VALUE);
The problem here is that Integer.MAX_VALUE - Integer.MIN_VALUE will overflow to -1.
The solution I came up with is to convert every Integer to a double before doing any operation
double percentage = ((double) input - (double) Integer.MIN_VALUE) * 100.0 / ((double) Integer.MAX_VALUE - (double) Integer.MIN_VALUE);
Some of the cast to a double can be omitted but for clarity I will leave all of them.
Is there a better and cleaner way to do this mapping?
Cleaner way :
Double input = 12d;
Double min = Double.valueOf(Integer.MIN_VALUE);
Double max = Double.valueOf(Integer.MAX_VALUE);
Double percentage = (input - min)*100.0/(max-min);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With