-5

I want code that i can get file size and change it to KB and MB

562 KB  =  562 KB
1024 KB =    1 MB
2152 KB = 2.15 MB

thank you in advance.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
Asca Asca
  • 1
  • 1
  • 1
  • 2

1 Answers1

6

Here it's:

public String size(int size){
    String hrSize = "";
    double m = size/1024.0;
    DecimalFormat dec = new DecimalFormat("0.00");

    if (m > 1) {
        hrSize = dec.format(m).concat(" MB");
    } else {
        hrSize = dec.format(size).concat(" KB");
    }
    return hrSize;
}

SOURCE: Converting KB to MB, GB, TB dynamically

Community
  • 1
  • 1
The Badak
  • 2,010
  • 2
  • 16
  • 28
  • 1
    On Android, there is a way to use [Formatter.formatFileSize(context: Context?, sizeBytes: Long): String!](https://developer.android.com/reference/kotlin/android/text/format/Formatter#formatfilesize) – Joonsoo Aug 07 '20 at 13:12