如何将数字与值的字母指针转换。示例:13486 至 13.4K

How to convert numbers with letters pointers of value. Example: 13486 to 13.4K

下面的代码很好地解决了指定的问题,但在 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; 
  }