public static String round(BigDecimal data, @NotNull Integer digit) {
/*1.判断要截取的数据是否为空,或者保留的位数是为大于零,如果不合理则返回*/
if (null == data || digit < 0) {
return null;
}
/*2.将传进来的数据进行分割,整数部分和小数部分*/
String[] dataArr = data.toString().split("\\.");
String integerPart = dataArr[0];
StringBuilder decimalPart = new StringBuilder(dataArr[1]);
/*3.判断小数部分位数和要求保留位数的关系*/
/*3.1 若果小数位数比要求保留位数少,后面自动补零*/
if (decimalPart.length() < digit) {
int difPlace = digit - decimalPart.length();
while (difPlace > 0) {
decimalPart.append("0");
difPlace--;
}
return integerPart + "." + integerPart;
}
String substring = decimalPart.substring(0, digit);
int bound = Integer.parseInt(String.valueOf(decimalPart.charAt(digit)));
/*3.3 判断截止位的值是否小于等于4,小于四则直接返回*/
if (bound < 4) {
return integerPart + "." + substring;
}
/*3.2 若果小数位数比要求保留位数多,根据截止位的值*/
char[] chars = substring.toCharArray();
/*3.3 执行进一操作*/
/*是否进位*/
boolean stepInto = true;
for (int i = chars.length - 1; i >= 0; i--) {
int value = Integer.parseInt(String.valueOf(chars[i]));
if (stepInto) {
if (value >= 9) {
value = 0;
chars[i] = String.valueOf((value)).charAt(0);
} else {
chars[i] = String.valueOf((value + 1)).charAt(0);
stepInto = false;
}
}
}
if (stepInto) {
integerPart = String.valueOf(Integer.parseInt(integerPart) + 1);
}
decimalPart.setLength(0);
for (char aChar : chars) {
decimalPart.append(aChar);
}
return integerPart + "." + decimalPart;
}
标签:四舍五入,digit,decimalPart,chars,valueOf,String,integerPart,BigDecimal
From: https://www.cnblogs.com/mingcodeing/p/16858473.html