public class PercentCount {
/**
* @param preNum 当前期
* @param sufNum 标准值
* @return 返回百分比
*/
public double percentBigDecimal(BigDecimal preNum, BigDecimal sufNum) {
double result = countDecimal(preNum, sufNum);
// if (result > 0) {
// return "+" + result + "%";
// }
// if (result < 0) {
// return result + "%";
// }
// if (result == 0) {
// return "+" + 0 + "%";
// }
// return null;
return result;
}
public double countDecimal(BigDecimal preNum, BigDecimal sufNum) {
boolean preBoolean = verifyNum(preNum);
boolean sufBoolean = verifyNum(sufNum);
//同时为true计算
if (preBoolean && sufBoolean) {
boolean b = verifyEqual(preNum, sufNum);
if (!b) {
return realCountDecimal(preNum, sufNum);
}
if (b) {
return 0;
}
}
if (!preBoolean && !sufBoolean) {
return 0;
}
if (!sufBoolean) {
return 100;
}
return 0;
}
//验证数字是否为零和null
public boolean verifyNum(BigDecimal num) {
if (null != num && num.compareTo(BigDecimal.ZERO) != 0) {
return true;
}
return false;
}
//验证两个数字是否相等
public boolean verifyEqual(BigDecimal preNum, BigDecimal sufNum) {
int n = preNum.compareTo(sufNum);
//比较 -1 小于 0 等于 1 大于
if (n == 0) {
return true;
}
return false;
}
//真正计算
public double realCountDecimal(BigDecimal preNum, BigDecimal sufNum) {
//(前面的数字-后面的数字)/后面的数字*100
BigDecimal bigDecimal = (preNum.subtract(sufNum)).divide(sufNum, 2, BigDecimal.ROUND_HALF_UP)
.multiply(new BigDecimal("100"));
if (bigDecimal.compareTo(BigDecimal.ZERO) != 0) {
return bigDecimal.doubleValue();
}
return 0;
}
public static void main(String[] args) {
PercentCount p = new PercentCount();
BigDecimal a = new BigDecimal("1");
BigDecimal b = new BigDecimal("1.1");
double percent = p.percentBigDecimal(a, b);
System.out.println(percent);
double result = (percent / 1);
System.out.println("初始值:"+result);
if (result >= 10) {
System.out.println(result);
} else {
result = result * 0.5 + 40;
System.out.println(result);
}
}
}