首页 > 技术文章 > java 对象转整数,两个整数相除转百分数

libin6505 2019-05-06 21:21 原文

 

 

public class MathUtil {
    
    public static void main(String[] args) {
        System.out.println(toPercent(1,3));
        System.out.println(toPercent(3,1));
    }
    
    //a/b转百分数字符串 (double)Math.round( a/(double)b*1000)/1000:保留3位小数四舍五入
    private static String toPercent(int a,int b) {
        if (a%b==0) {
            return a/b*100+"%";
        }else {
            return (double)Math.round( a/(double)b*1000)/10+"%";
        }
    }
    
    //Object转整数(失败返回null)
    private Integer toInt(Object o) {
        if (o!=null && !"".equals(o.toString())) {
            try {
                int parseInt = Integer.parseInt(o.toString());
                return parseInt;
            } catch (NumberFormatException e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }
}

 

推荐阅读