我正在尝试使用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(即没有外部库)来做到这一点?
答案 0 :(得分: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
答案 1 :(得分: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);
答案 2 :(得分: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));
答案 3 :(得分: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));