26

How can i convert number into K thousands M million and B billion suffix in jsp

e.g

1111 as 1.111 K etc

aioobe
  • 413,195
  • 112
  • 811
  • 826
jan5
  • 1,129
  • 3
  • 17
  • 28

3 Answers3

108

Adapting the answer from over here it should look something like

public static String withSuffix(long count) {
    if (count < 1000) return "" + count;
    int exp = (int) (Math.log(count) / Math.log(1000));
    return String.format("%.1f %c",
                         count / Math.pow(1000, exp),
                         "kMGTPE".charAt(exp-1));
}

Test code:

for (long num : new long[] { 0, 27, 999, 1000, 110592,
                             28991029248L, 9223372036854775807L })
   System.out.printf("%20d: %8s%n", num, withSuffix(num));

Output:

                   0:        0
                  27:       27
                 999:      999
                1000:    1.0 k
              110592:  110.6 k
         28991029248:   29.0 G
 9223372036854775807:    9.2 E
Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
5

//To remove zero from 1.0k

public static String coolNumberFormat(long count) {
        if (count < 1000) return "" + count;
        int exp = (int) (Math.log(count) / Math.log(1000));
        DecimalFormat format = new DecimalFormat("0.#");
        String value = format.format(count / Math.pow(1000, exp));
        return String.format("%s%c", value, "kMBTPE".charAt(exp - 1));
    }
Thomc
  • 202
  • 1
  • 4
  • 10
0
public String converter(double number) {
    Map<String, Double> suffixes = new HashMap<>();
    suffixes.put("K", 1000.0);
    suffixes.put("L", 100000.0);
    suffixes.put("M", 1000000.0);
    suffixes.put("Cr", 10000000.0);
    suffixes.put("B", 1000000000.0);
    suffixes.put("T", 1000000000000.0);

    for (Map.Entry<String, Double> entry : suffixes.entrySet()) {
        if (Math.abs(number) >= entry.getValue()) {
            number = number / entry.getValue();
            return DECIMAL_FORMAT.format(number) + entry.getKey();
        }
    }

    return DECIMAL_FORMAT.format(number);
}
  • 1
    where , public static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.00"); public static final double nullValue = 0.0; – user20864111 Dec 26 '22 at 11:01
  • It would be nice to give a brief explanation of how this works / how it solves the problem, and how it's different than existing answers. – starball Dec 27 '22 at 07:30