Tuesday, 13 October 2015

Adding Currency/ Float Values in Message mapping coming with Sign

There may be requirement when we need to add the incoming currency values or floating values coming in source file with +ve and -ve sign. PI can't handle these values directly in message mapping due to precision issue of computer. Hence we need to write a UDF to handle these values using BigDecimal dtatype provided by Java. If currency is coming in source file and you want to some addition its recommended to use BigDecimal instead of float and Double.
You may get correct result for values < 100 but it will fail if large number of values are coming in payload.


Below is the UDF for handling this:


Step1: Define a UDF sumOfCurrencies:



Step2: Write the below code to sum the currency:
/*
This function will add the debit and credit amount and will return the sum.
*/
int len = CurreStr.length;

BigDecimal sumpos = new BigDecimal(0 ); //Will hold sum of all +ve  values.
BigDecimal sumneg =  new BigDecimal(0 );  // Will hold sum of all -ve values
BigDecimal sum =  new BigDecimal(0 );       // Sum of positive and negative values (i.e. Total).
for(int i =0 ; i < len ; i++)
{
//All negative values will be added here
 if (CurreStr[i].indexOf("-") >= 0 )
 {
   BigDecimal big = new BigDecimal( CurreStr[i]);
    sumneg =sumneg.add(big) ;
 }
 else{
//All positive values will be added here
   BigDecimal big = new BigDecimal( CurreStr[i]);
   sumpos = sumpos.add(big);
     }

}
 sum =   sumpos.add(sumneg);
 result.addValue(sum);

Step3: Now use this node in your mapping.




Handle the context by changing the context on source Node.

No comments:

Post a Comment