2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Java Formatting or improve the readability of number like 1000 as 1k

I am looking for a solution which will formatted the number into below forms,

10000 - 10k

105000 - 105k

99755 - 99k etc

I got some solution from internet which are working as expected but not satisfied with the way of coding. Its lengthier and not optimistic. So still looking for a best solution which will give the result in an optimized way.

userimage

Please find your solution from here,


public class FormatNumbers {
    private static final char[] SUFFIXES = { 'k', 'm', 'g' };

    public static String format(long number) {
        if (number < 1000) {
            // No need to format this return String.valueOf(number);
        }
        // Convert to a string
        final String string = String.valueOf(number);
        // The suffix we're using, 1-based
        final int magnitude = (string.length() - 1) / 3;
        // The number of digits we must show before the prefix
        final int digits = (string.length() - 1) % 3 + 1;
        // Build the string
        char[] value = new char[4];
        for (int i = 0; i < digits; i++) {
            value[i] = string.charAt(i);
        }
        int valueLength = digits;
        // Can and should we add a decimal point and an additional number?
        if (digits == 1 && string.charAt(1) != '0') {
            value[valueLength++] = '.';
            value[valueLength++] = string.charAt(1);
        }
        value[valueLength++] = SUFFIXES[magnitude - 1];
        return new String(value, 0, valueLength);
    }
}
Answer is