1.获取千分位格式,保留两位小数,不足补0
public static String getThousands(Object number) {
try {
if (ObjectUtils.isEmpty(number)) {
return null;
}
if (number instanceof Number) {
BigDecimal bigDecimalObj = new BigDecimal(number.toString()).setScale(2, RoundingMode.HALF_UP);
DecimalFormat decimalFormat = new DecimalFormat("#,###.##");
String bigDecimalFormat = decimalFormat.format(bigDecimalObj);
boolean containsDot = bigDecimalFormat.contains(".");
if (!containsDot) {
bigDecimalFormat = bigDecimalFormat.concat(".");
}
String[] parts = bigDecimalFormat.split("\\.");
if (parts.length > 1) {
int decimalPlaces = parts[1].length();
int needDecimalPlaces = 2;
if (decimalPlaces < needDecimalPlaces) {
int zerosToAdd = needDecimalPlaces - decimalPlaces;
for (int i = 0; i < zerosToAdd; i++) {
bigDecimalFormat = bigDecimalFormat.concat("0");
}
}
} else {
bigDecimalFormat = bigDecimalFormat.concat("00");
}
return bigDecimalFormat;
}
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("");
}
return null;
}
2.数字保留两位小数,不足补0
public static String getRepairTwoZero(Object number) {
try {
if (ObjectUtils.isEmpty(number)) {
return null;
}
if (number instanceof Number) {
BigDecimal bigDecimalObj = new BigDecimal(number.toString()).setScale(2, RoundingMode.HALF_UP);
DecimalFormat decimalFormat = new DecimalFormat("##.##");
String bigDecimalFormat = decimalFormat.format(bigDecimalObj);
boolean containsDot = bigDecimalFormat.contains(".");
if (!containsDot) {
bigDecimalFormat = bigDecimalFormat.concat(".");
}
String[] parts = bigDecimalFormat.split("\\.");
if (parts.length > 1) {
int decimalPlaces = parts[1].length();
int needDecimalPlaces = 2;
if (decimalPlaces < needDecimalPlaces) {
int zerosToAdd = needDecimalPlaces - decimalPlaces;
for (int i = 0; i < zerosToAdd; i++) {
bigDecimalFormat = bigDecimalFormat.concat("0");
}
}
} else {
bigDecimalFormat = bigDecimalFormat.concat("00");
}
return bigDecimalFormat;
}
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("");
}
return null;
}