漂亮的数字格式算法

时间:2014-05-21 18:27:39

标签: java algorithm

将表示多个字节的整数转换为漂亮格式的算法。 最多3位数(不包括十进制数) - 例如像linux命令行一样。 没有领先或尾随的零 1K是1000字节

Examples:
Correct
123B -> 123B
12300B -> 12.3K
1910000B -> 1.91M
1000000000B -> 1G
83123 = 83.1K (not 83K)

Incorrect
012K (should be 12K)
8.20M (should be 8.2M)

我想知道我做错了什么,或者是否有更好的方法来解决这个问题,或者我的代码中是否有任何错误。

以下是我的解决方案(它有效,但我没有被选中,所以我不知道我做错了什么) -

/*
   * @Description - Function takes integer as input and returns the number in
   * pretty format(Gigabyte, Megabytes, KiloBytes, Bytes) with maximum of 3
   * digits
   * @param integer to convert to pretty format
   * @Assumptions - As mentioned in the problem set, 1000bytes = 1KB
   * Value is rounded to the nearest valid value
   * In java leading 0 in number is considered Octal, this function does not 
   * take care of octal to decimal conversion
   * As 1G = 1,000,000,000B the loop will run maximum 3 times in worst case 
   * Its requires constant space O(1) to store the result
   */
  static String fpretty(int num) {

    int count = 0;
    double div_result = (double) num;
    String display = "";

    /*
     * Every time we divide by 1000 count is incremented from B->K->M->G
     * Here two decimal places are preserved for cases like 1.05, 1.11
     * The output result of this loop will have 1,2 or 3 digits with max
     * two decimal places
     */
    while(div_result > 999.5) {
      div_result = div_result / 1000;
      div_result = Math.round(div_result * 100.0) / 100.0;
      count++;
    }

    // Get suffix B, K, M or G
    String measure = getUnit(count);

    // If decimal places is all zeros OR result has 3 digits
    if(div_result % 1 == 0 || div_result >= 100)
      display = (int)div_result + measure;
    // If result has 2 digits
    else if (div_result >= 10) {
      // Then fetch 1 decimal place as we have 2 digits
      div_result = (Math.round(div_result * 10.0) / 10.0);
      // If after rounding decimal places are .0 then truncate zeros 
      // eg. 99.97 rounded to -> 100.0 -> 100
      if(div_result % 1 == 0)
        display = (int)div_result + measure;
      else
        display = div_result + measure;
    }
    else
      display = div_result + measure;

    return display;
  }

1 个答案:

答案 0 :(得分:4)

使用DecimalFormat类可以轻松完成此操作。让它为你做舍入,可以用模式描述并选择RoundingMode舍入的方式。它还会处理尾随的零,这将被忽略。

public String pretty(int num) {
    DecimalFormat f = new DecimalFormat("###.##");
    f.setRoundingMode(RoundingMode.HALF_UP);
    double prettyd = num;
    int count = 0;
    while (prettyd >= 1000.0) {
        prettyd /= 1000.0;
        count++;
    }
    return f.format(prettyd) + getUnit(count);
}