Float Arithmetic Issue

Former Member
Former Member
Ok .. well this is a fun one and looking for suggestions. It is all about rounding of values and the result.

So .. have a TM value (long), incremented by 1 every second as well as another value named HR (also a long). These numbers could get relatively big.
The percent values are floats.

I do the following ..

Percent1 = (HRSum1 * 1.0 / TM * 1.0) * 100;
Percent2 = (HRSum2 * 1.0 / TM * 1.0) * 100;
Percent3 = (HRSum3 * 1.0 / TM * 1.0) * 100;
Percent4 = (HRSum4 * 1.0 / TM * 1.0) * 100;
Percent5 = (HRSum5 * 1.0 / TM * 1.0) * 100;

I could not have the percentage as a float but that would make them as numbers and likely then the end result will be less than 100 % due to being rounded down.

So for example .. I may get:

Percent 0 4.761905
Percent 1 9.523810
Percent 2 9.523810
Percent 3 9.523810
Percent 4 23.809524
Percent 5 42.857143

Which if you add them up .. you get 100.000002 .. but I do not want to display float values to the user.

If you round them .. you get I believe (this is from my head so I may be wrong) you get 102 as they are all rounding up in this case.

I need the 5 percentages to add up to 100% and displaying the ending percentages as a number

Here is an interesting thread about just this thing .. from another website.
http://stackoverflow.com/questions/13483430/how-to-make-rounded-percentages-add-up-to-100