Nancy P
Nancy P

Reputation: 57

How to round smoothly 100 percentage in Swift

I have an array of number which can be varied in length

let arrayNum = [1 ,5, 3, 12] // could also be [1, 5] or [1, 3, 5, 3, 1] 
let sum = arrayNum.reduce(0, +)

To calculate percentage of each element and display on a label, I use this method

 for value in arrayNum {
     percentageLabel.text = "\(value * 100 / sum) %"
 }

However, the percentage doesnt add up to 100%

1 has 4%
5 has 23%
3 has 14%
12 has 57%

total % is 99%

Does anyone have a better solution in this case? Thanks.

P.S I don't want them to have fraction values like 99.2% or 40.56%. I only want them to be 99% or 40%.

Upvotes: 1

Views: 1178

Answers (1)

matt
matt

Reputation: 535616

You are deliberately introducing a rounding error and then trying to pretend you didn't. That's never going to work.

It happens that for the particular cases you gave, you can solve the problem by rounding:

let arrayNum = [1 ,5, 3, 12] // could also be [1, 5] or [1, 3, 5, 3, 1] 
let sum = arrayNum.reduce(0, +)
for value in arrayNum {
    let d = (Double(value) * 100 / Double(sum)).rounded()
    let s = "\(Int(d))%"
    percentageLabel.text = s
}

5%
24%
14%
57%
[total is 100%]

But you cannot expect that approach to work universally; numbers just don't work that way. You have to be arithmetically honest.

Upvotes: 2

Related Questions