As we know using float in Java and performing operations like dividing and multiplying will not yield expect results, and for this reason alone, we are forced to use BigDecimal.
For a problem where 5 numbers are of the format XX.XXXXXXX (i.e., 6 digits after decimal), and their sum is exactly 100.0000000 and when we are asked to round off the numbers to two digits after decimal by keeping the sum of the numbers same as 100, here's the solution
double x = 10.00000000002+12;
System.out.println(""+x/2);
Output is 11.000000000010001
For a problem where 5 numbers are of the format XX.XXXXXXX (i.e., 6 digits after decimal), and their sum is exactly 100.0000000 and when we are asked to round off the numbers to two digits after decimal by keeping the sum of the numbers same as 100, here's the solution
package com.test;
import java.math.BigDecimal;
import java.math.RoundingMode;
/**
* @VinTech Blogs
*
*/
public class SumSame
{
public static void main( String[] args )
{
String[] from= {"3.2571365449","4.87608977397","5.29831575733","1.5684579238"};
BigDecimal[] fromBD = new BigDecimal[from.length];
BigDecimal[] toBD = new BigDecimal[from.length];
BigDecimal diff = new BigDecimal("0");
int high = 0;
int low = 0;
for(int i=0;i0) if(fromBD[i].compareTo(fromBD[high]) > 0){
high= i;
}else if(fromBD[i].compareTo(fromBD[low]) < 0){
low= i;
}
//set scale to 2 means 2 digits after decimal
// HALf_DOWN means 11.45 rounds to 11.4
//HALF_UP means 11.45 rounds to 11.5
toBD[i] = fromBD[i].setScale(2, RoundingMode.HALF_DOWN);
diff = diff.add(fromBD[i].subtract(toBD[i]));
}
//We get the difference here and allocate the diffs to highest or lowest based
//on diff value type
if(diff.doubleValue() > 0.0){
toBD[low]=toBD[low].add(diff).setScale(2,RoundingMode.HALF_DOWN);
}else if(diff.doubleValue() < 0.0){
toBD[high]=toBD[high].add(diff).setScale(2,RoundingMode.HALF_DOWN);
}
for (BigDecimal bigDecimal : toBD) {
System.out.println("val is "+bigDecimal);
}
}
}
0 comments:
Post a Comment