Android number reduction, language sensitivity

In my Android project, I hope to find a way to reduce the number sensitive to different locales. If the number is less than 1000, it should remain as it is; otherwise, I would like the number to be divided by the maximum possible power of 1000 and rounded to two decimal places. So far, I have the code below that correctly gives the desired results, as indicated in the "Exit" section.

public void formatNumbers() {
    //Output:
    //842 => 842
    //24,567 => 24.57k
    //356,915 => 356.92k
    //7,841,234 => 7.84M
    //1,982,452,873 => 1.98B
    int[] i = new int[] {842, 24567, 356915, 7841234, 1982452873};
    String[] abbr = new String[] {"", "k", "M", "B"};
    DecimalFormat df = new DecimalFormat("0.00");
    df.setRoundingMode(RoundingMode.HALF_UP);
    for (long i1 : i) {
        int thousands = thousands(i1);
        String result;
        if(thousands == 0) {
            result = String.valueOf(i1);
        } else {
            double d = (double) i1 / Math.pow(1000.0, thousands);
            result = df.format(d)+abbr[thousands];
        }
        System.out.println(i1 + " => " + result);
    }
}
public int thousands(double num) {
    //returns the number of times the number can be divided by 1000
    int n=0;
    double comp=1000.0;
    while(num>comp) {
        n++;
        comp*=1000.0;
    }
    return n;
}

, , . , DecimalFormat , , ; . , , ( , "" "" , ), , , , , , , . , , , . .

+4

Source: https://habr.com/ru/post/1605617/


All Articles