我有一个场景,我收到字符串形式的金额,我需要将其四舍五入并作为字符串发送,我所做的是:
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 行代码。
最佳答案
你的意思是:
return new BigDecimal(pfEmpWithoutRoundOff).setScale(0, RoundingMode.HALF_UP).toString();
?
关于java - 优化 BigDecimal 数四舍五入的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24691221/