2

I looked into how I could do this. I found an answer like this. But this is what I want 10200 -> 10k to be shown as 10.2k.

    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) {
  //Long.MIN_VALUE == -Long.MIN_VALUE so we need an adjustment here
  if (value == Long.MIN_VALUE) return format(Long.MIN_VALUE + 1);
  if (value < 0) return "-" + format(-value);
  if (value < 1000) return Long.toString(value); //deal with easy case

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

  long truncated = value / (divideBy / 10); //the number part of the output times 10
  boolean hasDecimal = truncated < 100 && (truncated / 10d) != (truncated / 10);
  return hasDecimal ? (truncated / 10d) + suffix : (truncated / 10) + suffix;
}
Hasan Kucuk
  • 2,433
  • 6
  • 19
  • 41
  • 6
    Have u check this https://stackoverflow.com/a/9769590/7666442 – AskNilesh Jul 19 '19 at 06:54
  • @NileshRathod Thanks it works fine. Would you add it as an answer? Because like me 1.2k vs 10.2k problem is not a problem for those who benefit from this question. – Hasan Kucuk Jul 19 '19 at 07:07
  • Didn't get you can you explain more – AskNilesh Jul 19 '19 at 07:12
  • @NileshRathod I've visited a lot of questions. The codes in the answers actually work. 1200 to 1.2k 10900 to 10k // what I wanted was that it was 10.9k. 1400000 to 1.4m others do not. So if you write this answer at the bottom, quote it. Friends who see this question can also be solved. The link you gave me worked for me. – Hasan Kucuk Jul 19 '19 at 07:15
  • 2
    I think the best approach would be to mark this question as a duplicate of the one linked by Nilesh, if the latter solved your problem – user2340612 Jul 19 '19 at 08:12

0 Answers0