Reputation: 8956
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.
Upvotes: 1
Views: 86
Reputation: 4302
Do you mean:
return new BigDecimal(pfEmpWithoutRoundOff).setScale(0, RoundingMode.HALF_UP).toString();
?
Upvotes: 1
Reputation: 4525
Try this one (if you like), it has only 2 lines for rounding-off the String
:
public static String roundOff(String pfEmpWithoutRoundOff) {
Long roundVal = Math.round(Double.valueOf(pfEmpWithoutRoundOff));
return roundVal.toString();
}
Upvotes: 1