Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map an Integer to a percentage [0,100]

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?

like image 736
Andrea Bergonzo Avatar asked Nov 28 '25 07:11

Andrea Bergonzo


1 Answers

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);
like image 81
Sahil Chhabra Avatar answered Nov 29 '25 20:11

Sahil Chhabra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!