1

I have a list of numbers (example):

98,
77,
55,
11

Which have combined value: 241

I tried to calculate the percentage using:

(int) (((double) quantity / totalQuantity) * 100);

This works (most of the times) however sometimes the combined percentage is not 100%. I tried to use Math.ceil or floor and I still encounter this problem.

edit:

Let me give a little background because you are right if my case was to calculate numbers: I have a shipment with has total number of items 241 and I have 4 types of items (98, 77, 55, 11). I need to show to the user how many percents each shipment is.

Thank you

2
  • 1
    @SeanBright One double is enough to make a calculation in doubles. Java will cast the int value to double automatically. Commented Sep 12, 2018 at 12:47
  • Since computer memory is limited, you cannot store numbers with infinite precision Commented Sep 13, 2018 at 7:44

2 Answers 2

6

This is normal, for example with numbers 5, 5, 5 you would get three times 33% which sums up to 99%.

The problem here is that rounding and addition are not interchangeable.

Sign up to request clarification or add additional context in comments.

1 Comment

There is literally no finite amount of decimal points that you can display to make this example add up to 100. Nice.
0

The question is related to mathematics, we have numbers that do not stop(repeating digit) when we perform division, for example three 2 + 1 + 1 its fraction average is 4/3 but its decimal average digits does not stop, so when you add the decimal 1.33 + 1.33 + 1.33 you don't get 4 rather 3.99 because we can not perform infinite number of division we stop at certain number of digits after the decimal point which results the averages may not sum up to the total exactly.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.