Reputation: 904
I am taking the sum 3 random existing whole numbers and then dividing each individual number by the sum to get the percentage.
What is the best way to guarantee I will always get 100%? Is there any vb.net function that will help me with this or do I basically have to manually find the difference between the sum of my 3 percentages and 100%, divide it, and add it to my 3 percentages.
Upvotes: 0
Views: 2005
Reputation: 141
This is a very common problem in statistical reporting and there is no real good way of handling it. To put it very blunt, the only way you can guarantee that rounded parts of a whole add up to the original whole every time, is to falsify your data. I know, this point of view is a little extreme, but nevertheless true. If you want to be true to your data, you should add up the rounded values and if they don’t add up to 100, display a footnote somewhere on your screen saying something like ”Percentages may not add up to 100 due to rounding”. The only way to represent the distribution correctly is by rounding them in the correct way.
Upvotes: 0
Reputation: 1093
How about rounding the last pie slice by subtracting the sum of the other slices from 100?
Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim percent1 As Decimal = 33.33333D
Dim percent2 As Decimal = 12D
Dim percent3 As Decimal = 100 - (percent1 + percent2)
Dim totalPercent As Decimal = percent1 + percent2 + percent3
MsgBox(totalPercent.ToString)
End Sub
End Class
Upvotes: 0
Reputation: 31203
You calculate the percentages, add all but the last together and subtract from 100. If you ry to distribute the error, it won't help since it would get rounded off like in the first calculation.
Sometimes it might be best to add the error to the largest number so it won't be that much off
Upvotes: 4