Search code examples
javabigdecimal

Optimize code for rounding off of a BigDecimal number


I have a scenario where i'm getting an amount in the form of String and I need to round it off and send as a String what I did is :

public static String roundOff(String pfEmpWithoutRoundOff) {
        try {

            BigDecimal bigDecimal = new BigDecimal(pfEmpWithoutRoundOff);
            int value = bigDecimal.intValue();
            int length = String.valueOf(value).length();
            BigDecimal rounded = bigDecimal.round(new MathContext(length, RoundingMode.HALF_UP));
            return String.valueOf(rounded);
        }
        catch(ArithmeticException e)
        {
            e.printStackTrace();
        }
        return null;

    }

Well is there a way I can optimize the code. I have some 5 lines which does it can I do it some 2-3 lines.


Solution

  • Do you mean:

    return new BigDecimal(pfEmpWithoutRoundOff).setScale(0, RoundingMode.HALF_UP).toString();
    

    ?