Java计算百分比

发布时间 2023-03-31 15:49:07作者: 陈省行

代码如下

    public static void main(String[] args) {
        float num = 3.14f;
        int total = 10;
        //创建一个数值格式化对象
        java.text.NumberFormat numberformat = java.text.NumberFormat.getInstance();
        //设置精确到小数点后2位
        numberformat.setMaximumFractionDigits(2);
        String result1 = numberformat.format(num / (float) total * 100);
        System.out.println("num和total的百分比是:result1=" + result1 + "%");
        //设置传入格式模板
        java.text.DecimalFormat df = new java.text.DecimalFormat("##.##%");
        String result2 = df.format(num / (float) total);
        System.out.println("num和total的百分比是:result2=" + result2);
    }

展示如下

image

参考

https://blog.csdn.net/m0_67401545/article/details/124812401