Java Data Type How to - Format an int value to a string that is in an approximate, but human readable format








Question

We would like to know how to format an int value to a string that is in an approximate, but human readable format.

Answer

import java.text.DecimalFormat;
//from   w ww .  j av  a2 s. co  m
public class Main {
  public static char COMMA = ',';
  public static String COMMA_STR = ",";
  public static char ESCAPE_CHAR = '\\';
  private static DecimalFormat oneDecimal = new DecimalFormat("0.0");
  
  /**
   * Given an integer, return a string that is in an approximate, but human 
   * readable format. 
   * It uses the bases 'k', 'm', and 'g' for 1024, 1024**2, and 1024**3.
   * @param number the number to format
   * @return a human readable form of the integer
   */
  public static String humanReadableInt(long number) {
    long absNumber = Math.abs(number);
    double result = number;
    String suffix = "";
    if (absNumber < 1024) {
      // nothing
    } else if (absNumber < 1024 * 1024) {
      result = number / 1024.0;
      suffix = "k";
    } else if (absNumber < 1024 * 1024 * 1024) {
      result = number / (1024.0 * 1024);
      suffix = "m";
    } else {
      result = number / (1024.0 * 1024 * 1024);
      suffix = "g";
    }
    return oneDecimal.format(result) + suffix;
  }
  public static void main(String[] argv){
    System.out.println(humanReadableInt(1000000000));
  }
}

The code above generates the following result.