Java BigDecimal舍入

时间:2014-04-15 18:24:38

标签: java rounding bigdecimal

我正在学习BigDecimal,我希望它能够检索我输入的确切数字,下面的代码正在编号,我不知道为什么

public static BigDecimal parseFromNumberString(String numberString) {

    if (numberString != null) {

        String nonSpacedString =
            numberString.replaceAll("[ \\t\\n\\x0B\\f\\r]", "").replaceAll("%", "");

        int indexOfComma = nonSpacedString.indexOf(',');
        int indexOfDot = nonSpacedString.indexOf('.');
        NumberFormat format = null;

        if (indexOfComma < indexOfDot) {
            nonSpacedString = nonSpacedString.replaceAll("[,]", "");
            format = new DecimalFormat("##.#");
        } else if (indexOfComma > indexOfDot) {
            nonSpacedString = nonSpacedString.replaceAll("[.]", "");    
            DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols();
            otherSymbols.setDecimalSeparator(',');
            format = new DecimalFormat("##,#", otherSymbols);
        } else {
            format = new DecimalFormat();
        }
        try {
            return new BigDecimal(format.parse(nonSpacedString).doubleValue(), new MathContext(12));
        } catch (ParseException e) {
            // unrecognized number format
            return null;
        }
    }
    return null;
}

如果我做的话

public static void main(String[] args){
    BigDecimal d = Test.parseFromNumberString("0.39");
    System.out.println(d);  
}

打印的值是0,00而不是0.39

2 个答案:

答案 0 :(得分:1)

试试这段代码:

public static BigDecimal parseFromNumberString(String numberString) {

    if (numberString != null) {

        String nonSpacedString =
            numberString.replaceAll("[ \\t\\n\\x0B\\f\\r]", "").replaceAll("%", "");

        int indexOfComma = nonSpacedString.indexOf(',');
        int indexOfDot = nonSpacedString.indexOf('.');
        DecimalFormat decimalFormat = new DecimalFormat();
        DecimalFormatSymbols symbols = new DecimalFormatSymbols();
        String pattern = "#0.0#";           

        if (indexOfComma < indexOfDot) {
            symbols.setDecimalSeparator('.');
        } else if (indexOfComma > indexOfDot) {
            symbols.setDecimalSeparator(',');
        } 

        try {
            decimalFormat = new DecimalFormat(pattern, symbols);
            decimalFormat.setParseBigDecimal(true);
            BigDecimal toRet = (BigDecimal) decimalFormat.parse(nonSpacedString);
            return toRet.setScale(12);
        } catch (ParseException e) {
            return null;
        }
    }
    return null;
}

public static void main(String... args) {
    BigDecimal d = Test.parseFromNumberString("0,39");
    System.out.println(d);  
}

这就是你想要的吗?

答案 1 :(得分:0)

我刚刚运行了你的代码而且我得到了。 0.390000000000也许你忘了保存?

尝试清理项目,重新启动ide并重新编译。代码应该可以正常工作