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() {
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) {
int n=0;
double comp=1000.0;
while(num>comp) {
n++;
comp*=1000.0;
}
return n;
}
, , . , DecimalFormat , , ; . , , ( , "" "" , ), , , , , , , . , , , . .