1

我正在尝试使用BigDecimal.ROUND_HALF_UP但没有得到预期的结果。这段代码:

String desVal="21.999";  
BigDecimal decTest=new BigDecimal(
    String.valueOf(desVal)
)
.setScale(
    Integer.parseInt(decimalPlaces), BigDecimal.ROUND_DOWN
);     
System.out.println(decTest); 

给出以下结果:

decimalPlaces=1 it is displaying 21.9 //correct 
decimalPlaces=2 displaying 21.99 //correct 
decimalplaces=3 displaying 21.999 //correct 
decimalplaces=4 displaying 21.9990 //incorrect 

我想得到以下信息:

decimalPlaces=1 should display 21.9      
decimalPlaces=2 should display 21.99 
decimalplaces=3 should display 21.999 
decimalplaces=4 should display 21.999 

有没有办法用标准Java(即没有外部库)来做到这一点?

4

4 回答 4

3

使用BigDecimal#stripTrailingZeros()

String[] decimalPlaces = new String[] {"2", "2", "3", "4", "4"};
String[] desVal = new String[] {"20", "21.9", "21.90", "21.99999", "21.99990"};

for (int i = 0; i < desVal.length; i++) {
    BigDecimal decTest = new BigDecimal(desVal[i]);

    if (decTest.scale() > 0 && !desVal[i].endsWith("0") &&  !(Integer.parseInt(decimalPlaces[i]) > decTest.scale())) {
        decTest = decTest.setScale(Integer.parseInt(decimalPlaces[i]),
                BigDecimal.ROUND_DOWN).stripTrailingZeros();
    }
    System.out.println(decTest);
}

输出:

20
21.9
21.90
21.9999
21.99990
于 2013-06-26T13:46:18.577 回答
0
int decPlaces = Math.min(Integer.parseInt(decimalPlaces), 
                         desVal.length() - desVal.indexOf(".") + 1);
BigDecimal decTest=
      new BigDecimal(String.valueOf(desVal)).
             setScale(decPlaces, BigDecimal.ROUND_DOWN);
于 2013-06-26T13:46:05.257 回答
0

您可以使用 java.text.NumberFormat

NumberFormat nf = NumberFormat.getInstance();

System.out.println(nf.format(decTest));

如果要保留原始比例,则

String desVal="21.99901";  
BigDecimal decTest=new BigDecimal(String.valueOf(desVal)); 
int origScale = decTest.scale();
decTest = decTest.setScale(4, BigDecimal.ROUND_DOWN);
System.out.println(String.format("%."+origScale+"f", decTest));
于 2013-06-26T13:51:36.753 回答
0

如果要打印尾随零,但不是全部,则需要DecimalFormat。诀窍是,在您的情况下,您需要根据原始输入字符串中的小数位数来构建格式字符串。

    int decimalPlaces = 10;
    String desVal="21.99900";  

    // find the decimal part of the input (if there is any)
    String decimalPart = desVal.contains(".")?desVal.split(Pattern.quote("."))[1]:"";

    // build our format string, with the expected number of digits after the point
    StringBuilder format = new StringBuilder("#");
            if (decimalPlaces>0) format.append(".");
    for(int i=0; i<decimalPlaces; i++){
        // if we've passed the original decimal part, we don't want trailing zeroes
        format.append(i>=decimalPart.length()?"#":"0");
    }

    // do the rounding
    BigDecimal decTest=new BigDecimal(
        String.valueOf(desVal)
    )
    .setScale(
        decimalPlaces, BigDecimal.ROUND_DOWN
    );   

    NumberFormat nf = new DecimalFormat(format.toString());
    System.out.println(nf.format(decTest));
于 2013-06-26T14:32:38.163 回答