3

The below code solves the specified question very well, but in cases of 5 digits it does not. For example, it does well with this scenario 1345 to 1.3k, but it does not work with 13547 to 13.5k please help me out This is the code below

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;
    }
}
halil
  • 800
  • 16
  • 33
  • 4
    P.S.: The code which OP has posted is taken from here [How to go about formatting 1200 to 1.2k in java](http://stackoverflow.com/a/30661479/2815219) – Raman Sahasi Mar 13 '17 at 10:10
  • 3
    This line: `boolean hasDecimal = truncated < 100 && (truncated / 10d) != (truncated / 100);` should actually be `boolean hasDecimal = truncated < 100 && (truncated / 10d) != (truncated / 10);`. You did not copy the code well, as in the answer from the post mentioned by @RamanSahasi – Andrei Olar Mar 13 '17 at 10:11
  • Yes that is what i noted with that in mind the code solves only a couple of scenarios but excluding some like for example in the noted case where i have 13489 to 13.4k it does fix that that is the help i would like i appreciate your code though if any change to fix the scenario please let me know. – Brian Ombisa Mar 13 '17 at 10:14
  • I have change but when i run it its different as expected. It gives me 13K instead of 13.4K for this figure 13481 – Brian Ombisa Mar 13 '17 at 10:19

1 Answers1

2

Just use 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; 
  }
freedev
  • 25,946
  • 8
  • 108
  • 125