0

Possible Duplicate:
Format file size as MB, GB etc

Using NumberFormat, I would like to have my numbers formatted as scientific multipliers. In other words, I would like to have the following formatting:

  • 1024 should be formatted as 1K
  • 1048576 should be formatted as 1G

And obviously other numbers should be expressed using k, G, and other multiples.

How can I do that ? Or do I need some Java library ?

Community
  • 1
  • 1
Riduidel
  • 22,052
  • 14
  • 85
  • 185
  • This might help you: http://stackoverflow.com/questions/4753251/how-to-go-about-formatting-1200-to-1-2k-in-java – Maroun Jan 18 '13 at 13:39

3 Answers3

5

Roughly, this should work. It needs some polishing regarding proper double formatting.

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;
}
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
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());
    }

}
Shashi
  • 12,487
  • 17
  • 65
  • 111
-1

Maybe that? How to convert byte size into human readable format in java?

Community
  • 1
  • 1
salomon
  • 1,219
  • 1
  • 8
  • 9