Skip to content

Instantly share code, notes, and snippets.

@laaptu
Created October 22, 2013 05:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laaptu/7095577 to your computer and use it in GitHub Desktop.
Save laaptu/7095577 to your computer and use it in GitHub Desktop.
Properly calculating sum to percentage with rounding error to +-1%
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