Java 优化用于对大十进制数进行舍入的代码

Java 优化用于对大十进制数进行舍入的代码,java,bigdecimal,Java,Bigdecimal,我有一个场景,我得到一个字符串形式的金额,我需要将其四舍五入并作为字符串发送,我所做的是: public static String roundOff(String pfEmpWithoutRoundOff) { try { BigDecimal bigDecimal = new BigDecimal(pfEmpWithoutRoundOff); int value = bigDecimal.intValue();

我有一个场景,我得到一个字符串形式的金额,我需要将其四舍五入并作为字符串发送,我所做的是:

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行。试试这一行(如果你喜欢的话),它只有两行代码,可以把字符串四舍五入:

public static String roundOff(String pfEmpWithoutRoundOff) {
    Long roundVal = Math.round(Double.valueOf(pfEmpWithoutRoundOff));
    return roundVal.toString();
}
你是说:

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

它可能属于我,我在想是否有人能帮我解决这个问题,也许是字符串格式?数量真的很大吗?格式(Locale.US,“%.2f”,rawprice)@Ivan Ivanov想要BigDecimal格式,只是为了安全起见,以防出现大的金额我不想冒险使用long或double我想要BigDecimal然后使用
新的BigDecimal(pfEmpWithoutRoundOff)。setScale(0,RoundingMode.HALF_UP)
,正如Michael建议的那样。如何使用setScale()如果不同的输入字符串有不同的比例?我不明白你的意思。你能给我举几个例子吗?你希望什么样的输入有什么样的输出?好吧,我用setScale()误解了MathContext()的int setPrecision。它是在做工作(grt:)