Created
October 22, 2013 05:19
-
-
Save laaptu/7095577 to your computer and use it in GitHub Desktop.
Properly calculating sum to percentage with rounding error to +-1%
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
float a = 221, b = 77, c = 17, d = 88, e = 22, f = 44; | |
float total = a + b + c + d + e + f; | |
int sum = (int) Math.round(100.0 / total * a) | |
+ (int) Math.round(100.0 / total * b) | |
+ (int) Math.round(100.0 / total * c) | |
+ (int) Math.round(100.0 / total * d) | |
+ (int) Math.round(100.0 / total * e) | |
+ (int) Math.round(100.0 / total * f); | |
System.out.println(Math.round(100.0 / total * a)); | |
System.out.println(Math.round(100.0 / total * b)); | |
System.out.println(Math.round(100.0 / total * c)); | |
System.out.println(Math.round(100.0 / total * d)); | |
System.out.println(Math.round(100.0 / total * e)); | |
System.out.println(Math.round(100.0 / total * f)); | |
System.out.println(sum); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment