大家好我想把关注者数量转换为像Instagram这样的可读字符串。为此,我使用下面的代码:
public static String new_format(double number)
{
String[] suffix = new String[]{"","K", "M", "B", "T"};
int MAX_LENGTH = 4;
String r = new DecimalFormat("##0E0").format(number);
r = r.replaceAll("E[0-9]", suffix[Character.getNumericValue(r.charAt(r.length() - 1)) / 3]);
while(r.length() > MAX_LENGTH || r.matches("[0-9]+\\.[a-z]"))
{
r = r.substring(0, r.length()-2) + r.substring(r.length() - 1);
}
return r;
}
但它没有给出正确的价值,例如lelepons有24.2米粉丝,但它显示了20米。我从这里获得了这段代码https://stackoverflow.com/a/49405728/9565955
答案 0 :(得分:1)
public String formatValue(double value) {
int power;
String suffix = " kmbt";
String formattedNumber = "";
NumberFormat formatter = new DecimalFormat("#,###.#");
power = (int)StrictMath.log10(value);
value = value/(Math.pow(10,(power/3)*3));
formattedNumber=formatter.format(value);
formattedNumber = formattedNumber + suffix.charAt(power/3);
return formattedNumber.length()>4 ? formattedNumber.replaceAll("\\.[0-9]+", "") : formattedNumber;
}
在OnCreateView中调用此方法来设置此方法的返回值
userfollower.setText(formatValue(number));