package org.sxkj.common.utils;
|
|
import com.alibaba.cloud.commons.lang.StringUtils;
|
|
import java.math.BigDecimal;
|
import java.math.RoundingMode;
|
import java.text.DecimalFormat;
|
import java.util.Objects;
|
import java.util.Optional;
|
|
public class NoNullUtils {
|
|
/**
|
* null->0 精确长度2
|
*
|
* @param data BigDecimal 返回不为null的数
|
* @return
|
*/
|
public static BigDecimal bigDecimal(BigDecimal data) {
|
return Optional.ofNullable(data).
|
orElse(BigDecimal.ZERO).
|
setScale(2, BigDecimal.ROUND_HALF_UP);
|
}
|
|
/**
|
* null->0 ,精确长度 4
|
*
|
* @param data
|
* @return
|
*/
|
public static BigDecimal bigDecimalPointFour(BigDecimal data) {
|
return Optional.ofNullable(data).
|
orElse(BigDecimal.ZERO).
|
setScale(4, BigDecimal.ROUND_HALF_UP);
|
}
|
|
/**
|
* null->0
|
*
|
* @param data
|
* @return
|
*/
|
public static Integer integer(Integer data) {
|
return Optional.ofNullable(data).orElse(0);
|
}
|
/**
|
* null->0.0
|
*
|
* @param data
|
* @return
|
*/
|
public static Double doubleValue(Double data) {
|
return Optional.ofNullable(data).orElse(0.0);
|
}
|
|
public static Long longValue(Long data) {
|
return Optional.ofNullable(data).orElse(0L);
|
}
|
|
/**
|
* str-> inter
|
*
|
* @param num
|
* @return
|
*/
|
public static Integer strDefaultZero(String num) {
|
if (StringUtils.isEmpty(num)) {
|
return 0;
|
}
|
Integer result = 0;
|
try {
|
result = Integer.valueOf(num);
|
} catch (Exception e) {
|
result = 0;
|
}
|
return result;
|
}
|
|
/**
|
* 不为空的dd
|
* @param d
|
* @return
|
*/
|
public static Double getNoNullDouble(Double d,Integer scale) {
|
Double result = Optional.ofNullable(d).orElse(0d);
|
return new BigDecimal(result).setScale(scale, RoundingMode.HALF_UP).doubleValue();
|
}
|
|
|
/**
|
* 不为空的dd
|
* @param d
|
* @return
|
*/
|
public static Float getNoNullFloat(Float d,Integer scale) {
|
return new BigDecimal(d).setScale(scale, RoundingMode.HALF_UP).floatValue();
|
}
|
|
/**
|
* 格式化的比例
|
*
|
* @param num 数量
|
* @param totalNum 总数量
|
* @return 数量/总数量 百分比
|
*/
|
public static String getFormatRate(Integer num, Integer totalNum) {
|
String rate = "0";
|
if (Objects.nonNull(num) && Objects.nonNull(totalNum) && totalNum > 0 && num > 0) {
|
double percentage = (double) num / totalNum * 100;
|
DecimalFormat df = new DecimalFormat("0.0"); // 保留 2 位小数
|
rate = df.format(percentage);
|
}
|
return rate;
|
}
|
|
}
|