0

可能重复:
将文件大小格式化为 MB、GB 等

使用NumberFormat,我想将我的数字格式化为科学乘数。换句话说,我希望有以下格式:

  • 1024 应格式化为 1K
  • 1048576 应格式化为 1G

显然,其他数字应该使用 k、G 和其他倍数来表示。

我怎样才能做到这一点 ?还是我需要一些 Java 库?

4

3 回答 3

5

粗略地说,这应该有效。double它需要一些关于正确格式的抛光。

static String formatSize(double size) {
  String finalQ = "";
  for (String q: new String[] {"k", "M", "G"}) {
    if (size < 1024) break;
    finalQ = q;
    size /= 1024;
  }
  return size + finalQ;
}
于 2013-01-18T13:40:50.813 回答
0
package com.shashi.mpoole;


public class MetricPrefix {

    static int ONE_ZERO_TWO_FOUR = 1024;
    static String SEPARATOR = " ";
    enum SIZE
    {
        B, K, M, G, T, P, E, Z, Y;
//      BYTE, KILO, MEGA, GIGA, TERA, PETA, EXA, ZETTA, YOTTA;
    }

    class Result
    {
        int number = 0;
        SIZE size;



        public Result setNumber(int number)
        {
            this.number = number;
            return this;
        }

        public Result setSize(SIZE size)
        {
            this.size = size;
            return this;
        }

        public String getValue()
        {
            return this.number + SEPARATOR + this.size; 
        }
    }

    public Result getResult(double howMuchBigger)
    {
        double bigNumber = howMuchBigger;
        int index = 0;
        while(howMuchBigger-ONE_ZERO_TWO_FOUR>0)
        {
            bigNumber = howMuchBigger;
            howMuchBigger = howMuchBigger/ONE_ZERO_TWO_FOUR;
            index++;
        }

        if(index == 0)
            return new Result().setNumber((int) (bigNumber)).setSize(SIZE.values()[index]); 
        else
        return new Result().setNumber((int) (bigNumber/ONE_ZERO_TWO_FOUR)).setSize(SIZE.values()[index]);

    }

    public static void main(String[] args) {

        MetricPrefix j = new MetricPrefix();
        System.out.println(j.getResult(56).getValue());
    }

}
于 2013-01-18T14:23:28.013 回答
-1

也许是这样?如何在java中将字节大小转换为人类可读的格式?

于 2013-01-18T13:42:06.213 回答