java - Rounding Off to 2 decimal places giving issues while summing up -


getting following sets of numbers -->

[5.1429,5.1429,5.1429,5.1429,5.1429,5.1429,5.1426] [0.8333,0.8333,0.8333,0.8333,0.8333,0.8335] 

when added, these give whole number.

now have display these numbers after rounding 2 decimal places -->

[5.14, 5.14, 5.14, 5.14, 5.14, 5.14, 5.14] [0.83, 0.83, 0.83, 0.833, 0.83, 0.83] 

which not summing whole number. causing whole total come 99.96 or 101.01.

is there way can round numbers total comes whole number.

i not looking way round off sum. looking way manipulate rounded numbers (like 5.14,5.14.. etc) give whole number. (if there way.. :) )

you introduce smallest absolute rounding error - while keeping total sum intact - if sort inputs decreasing third decimal , round down, except enough numbers reach target.

as simple example:

input

0.132, 0.226, 0.257, 0.385 // sums 1.00 

sort 3rd decimal (descending)

0.257, 0.226, 0.385, 0.132 

round down

0.25, 0.22, 0.38, 0.13 // sums 0.98 

round enough reach whole number

0.26, 0.23, 0.38, 0.13 // sums 1.00 

in code (untested):

public void printrounded(double[] ds) {     // create wrapper objects     int n = ds.length;     wrapper[] ws = new wrapper[n];     (int = 0; < n; i++)         ws[i] = new wrapper(i, (int)(ds[i] * 1000) % 10, (int)(ds[i] * 100));      // sort third decimal, descending     arrays.sort(ws, new comparator<wrapper>() {         public int compare(wrapper o1, wrapper o2) {             return o2.thirddecimal.compareto(o1.thirddecimal);         }     });      // find number of elements must rounded , increment     int sum = 0;     (int = 0; < n; i++)         sum += ws[i].prefix;     int numbertoincrement = 100 - (sum % 100);     (int = 0; < numbertoincrement ; i++)         ws[i].prefix++;      // sort input order     arrays.sort(ws, new comparator<wrapper>() {         public int compare(wrapper o1, wrapper o2) {             return o1.index.compareto(o2.index);         }     });      // print values     (int = 0; < n; i++) {         system.out.println(ws[i].prefix / 100 + "." ws[i].prefix % 100);     } }  private class wrapper {     public wrapper(int index, int thirddecimal, int prefix) {         this.index = index;         this.thirddecimal = thirddecimal;         this.prefix = prefix;     }      public int index;     public int thirddecimal;     public int prefix; } 

instead of using custom formatting of course convert ints double , use standard formatting.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -