Search code examples
javastringtype-conversiontalendbigdecimal

How to convert a String with decimals to BigDecimal and keep the decimals, in Talend Java?


I'm creating a Job in Talend to transform data from a .csv file using some data from a database and then incorporate into another .csv file. During the transformation some calculation is needed to be performed on the values:

value1 / value2 * value3

Value1 is taken from the .csv file and is by default a String representing an amount, f.e.

"15.25"

Values 2 and 3 are taken from database and are BigDecimals with 4 decimal places. The result of the calculation must be rounded up to 2 decimal places.

My question is: How to convert data from .csv file so that it could be calculated with BigDecimals from database?

If I convert any datatype to BigDecimal it loses the decimals, f.e from String: BigDecimal n = new BigDecimal("15.25") The result would always be

15

I'v tried to do it with math context ROUND_UNNECESSARY and setScale also, but this seems not be relevant in this cases.


Solution

  • You can use BigDecimal

    BigDecimal v1 = new BigDecimal("15.25");
    BigDecimal v2 = new BigDecimal("5.25");
    BigDecimal v3 = new BigDecimal("1.15");
    
    BigDecimal v123 = v1.divide(v2, MathContext.DECIMAL64).multiply(v3);
    
    System.out.println(v123);
    System.out.println(v123.setScale(2, RoundingMode.HALF_UP));
    

    prints

    3.34047619047619075
    3.34
    

    To perform this calculation using double

    double v1 = 15.25;
    double v2 = 5.25;
    double v3 = 1.15;
    double v123 = v1 / v2 * v3;
    System.out.println(v123);
    System.out.printf("%.2f%n", v123);
    

    prints

    3.34047619047619
    3.34
    

    If MathContext.DECIMAL128 had been used, the unrounded value would be

    3.340476190476190476190476190476191
    

    and in this example, both solutions are more than accurate enough.