天天看點

java計算資料的百分比

概述

有這樣一個需求,需要計算一個集合中的資料占集合總數的百分比,這裡做一個簡單的記錄。

java計算資料的百分比

實作代碼如下:

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Test3 {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(15);
        list.add(21);
        list.add(41);
        // 計算集合資料的總數
        int sum = list.stream().mapToInt(value -> value).sum();
        System.out.println("print getPercent -------------");
        List<String> collect = list.stream().map(a -> getPercent(a, sum)).collect(Collectors.toList());
        System.out.println(collect.toString());
        System.out.println("print getPercent2 ------------");
        List<String> collect2 = list.stream().map(a -> getPercent2(a, sum)).collect(Collectors.toList());
        System.out.println(collect2.toString());


    }

    /**
     * 方式一:使用java.text.NumberFormat實作
     * @param x
     * @param y
     * @return
     */
    public static String getPercent(int x, int y) {
        double d1 = x * 1.0;
        double d2 = y * 1.0;
        NumberFormat percentInstance = NumberFormat.getPercentInstance();
        // 設定保留幾位小數,這裡設定的是保留兩位小數
        percentInstance.setMinimumFractionDigits(2);
        return percentInstance.format(d1 / d2);
    }

    /**
     * 方式二:使用java.text.DecimalFormat實作
     * @param x
     * @param y
     * @return
     */
    public static String getPercent2(int x, int y) {
        double d1 = x * 1.0;
        double d2 = y * 1.0;
        // 設定保留幾位小數, “.”後面幾個零就保留幾位小數,這裡設定保留四位小數
        DecimalFormat decimalFormat = new DecimalFormat("##.0000%");
        return decimalFormat.format(d1 / d2);
    }


}

           
java計算資料的百分比