我有一个场景,我以字符串的形式获得金额,我需要将其四舍五入并作为字符串发送我所做的是:
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;
}
有没有办法优化代码。我有5行,它可以做到2-3行。
答案 0 :(得分:1)
试试这个(,如果你喜欢),它只有 2行来舍入String
:
public static String roundOff(String pfEmpWithoutRoundOff) {
Long roundVal = Math.round(Double.valueOf(pfEmpWithoutRoundOff));
return roundVal.toString();
}
答案 1 :(得分:1)
你的意思是:
return new BigDecimal(pfEmpWithoutRoundOff).setScale(0, RoundingMode.HALF_UP).toString();