I have a csv file where amount and quantity fields are present in each detail record except header and trailer record. Trailer record has a total charge values which is the total sum of quantity multiplied by amount field in detail records . I need to check whether the trailer total charge value is equal to my calculated value of amount and quantity fields. I am using the double data type for all these calculations
In the csv file amount field appears as “10.12” or “10” or “10.0” or “10.456” or “10.4555” or “-10.12”. Also amount can have a positive or negative value.
In csv file
H,ABC…..
“D”,….,”1″,”12.23″
“D”,…..,”3″,”-13.334″
“D”,……,”2″,”12″
T,csd,123,12.345
—————————— While Validation i am having the below code ——————–
double detChargeCount =0;
//From csv file i am reading trailer records charge value
String totChargeValue = items[3].replaceAll("\"","").trim();
if (null != totChargeValue && !totChargeValue.equals("")) {
detChargeCount = new Double(totChargeValue).doubleValue();
if(detChargeCount==calChargeCount)
validflag=true;
———————–While reading CSV File i am having the below code
if (null != chargeQuan && !chargeQuan.equals("")) {
tmpChargeQuan=Long(chargeQuan).longValue();
}
if (null != chargeAmount && !chargeAmount.equals("")) {
tmpChargeAmt=new Double(chargeAmount).doubleValue();
calChargeCount=calChargeCount+(tmpChargeQuan*tmpChargeAmt);
}
I had declared the variables tmpChargeQuan, tmpChargeAmt, calChargeCount as double
When i searched web i came to know that double might give issues for financial calculations so need to use BIGDECIMAL. But i am wondering is this scenario applies for my calculation. In my case amount value can have upto 5 or 6 digits after the decimal point” Can i use double datatype for this calculation? I am using it for validation. Will it create an problem if i use the above code with multiplication using double?
I’ll expand on what Adeel has already succintly answered. You can fit those numbers into a double datatype. The problem is when numbers get calculated, will they get calculated correctly? The answer is no – they will not. Generally it’s not that much of a problem if you account for that with a delta, that is, your leeway in assuming whether or not a double value is equivalent to another double value. But for calculations involving exact numbers, such as monetary calculations, you must use a type such as BigDecimal to hold the values.
When you have this number:
1.23445
as a double, it may look like 1.23445
but it may actually be something like
1.234450000003400345543034
When you perform multiple calculations on numbers such as that, generally those extra places don’t matter – however, over time, they will yield inaccurate results. With BigDecimal, when a number is specified as its String representation, it is that number – it does not suffer the “almost as good” problem doubles do.
I am updating this answer to include some notes from the double constructor of BigDecimal, found at this address.