除法保留任意位小数小算法

话不多说直接上代码,很简单,只是做以总结以后直接拿来用了。


import java.math.BigDecimal;
public static void main(String args[]){
    String rate = divisionFunction("1","2",2);
    System.out.println(rate+"%");
}

/**
* @definition 除法运算
* @author edward
* @param num:分子;totalNum:分母;scale:保留几位小数
**/

public static String divisionFunction(String num, String totalNum, int scale){
    double res = 0.0;
    //判断分母不为0
    if("".equals(totalNum)||null==totalNum||"0".equals(totalNum)){
        totalNum = "0";
    }else {
        //判断分子
        if("".equals(num)||null==num){
            num = "0";
        }
        double a = Double.valueOf(num);
        double b = Double.valueOf(totalNum);
        BigDecimal bd1 = new BigDecimal(Double.toString(a));
        BigDecimal bd2 = new BigDecimal(Double.toString(b));
        double div = bd1.divide(bd2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
        res = div * 100;
    }
    return String.valueOf(res);
}

 

 

你可能感兴趣的:(经验总结)