java - 如何将数字与值的字母指针转换。示例 : 13486 to 13. 4K

标签 java android android-studio truncation

下面的代码很好地解决了指定的问题,但在 5 位数字的情况下却没有。例如,它在 1345 到 1.3k 的情况下效果很好,但在 13547 到 13.5k 的情况下不起作用,请帮帮我 这是下面的代码

private static final NavigableMap<Long, String> suffixes = new TreeMap<>();
    static {
        suffixes.put(1_000L, "k");
        suffixes.put(1_000_000L, "M");
        suffixes.put(1_000_000_000L, "G");
        suffixes.put(1_000_000_000_000L, "T");
        suffixes.put(1_000_000_000_000_000L, "P");
        suffixes.put(1_000_000_000_000_000_000L, "E");
    }

    public static String format(long value) {

        if (value == Long.MIN_VALUE) return format(Long.MIN_VALUE + 1);
        if (value < 0) return "-" + format(-value);
        if (value < 1000) return Long.toString(value);

        Map.Entry<Long, String> e = suffixes.floorEntry(value);
        Long divideBy = e.getKey();
        String suffix = e.getValue();

        long truncated = value / (divideBy / 10);
        boolean hasDecimal = truncated < 100  && (truncated / 10d) != (truncated / 100);
        return hasDecimal ? (truncated / 10d) + suffix : (truncated / 10) + suffix;
    }
}

最佳答案

只需使用String.format

  public static String format(long value) {

      if (value == Long.MIN_VALUE) return format(Long.MIN_VALUE + 1);
      if (value < 0) return "-" + format(-value);
      if (value < 1000) return Long.toString(value);

      Map.Entry<Long, String> e = suffixes.floorEntry(value);
      Long divideBy = e.getKey();
      String suffix = e.getValue();

      long truncated = value / divideBy;
      double withDecimals = (value*1.0) / divideBy;
      boolean hasDecimal = (withDecimals != Math.floor(withDecimals));
      return !hasDecimal ? truncated + suffix : String.format("%.1f", withDecimals) + suffix; 
  }

关于java - 如何将数字与值的字母指针转换。示例 : 13486 to 13. 4K,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42760970/

相关文章:

Android Studio - 无法下载 Artifact

Java JMenuBar 未添加或正确显示

java - 为什么SpringApplication启动后不立即终止?

javascript - Uncaught ReferenceError : PhoneGap is not Defined

android - 在 API 8 中使用加载器

java - 使用注释处理生成单元测试

android - 添加约束布局障碍在Android Android Studio的上下文菜单中丢失

java - 无法 @Query 查找 ElementCollection 中具有匹配枚举的实体

java - Android 中的 "foreign application"是什么?

android - 我是否需要真正的 Android 设备才能为 Marketplace 开发 Android 应用程序?