Java Size getSizeString(long bytes)

Here you can find the source of getSizeString(long bytes)

Description

Create a formatted string with the given number of bytes in the highest reasonable unit, like 512 B, 1,3 KB or 2 MB.

License

Open Source License

Parameter

Parameter Description
bytes a parameter

Return

the formatted string

Declaration

public static String getSizeString(long bytes) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.text.NumberFormat;
import java.util.Locale;

public class Main {
    /**//from  w w  w  .  ja  v  a 2  s .  c  o  m
     * Create a formatted string with the given number of bytes in the highest reasonable unit, like 512 B, 1,3 KB or 2 MB.
     *
     * @param bytes
     * @return the formatted string
     */
    public static String getSizeString(long bytes) {
        NumberFormat nf = NumberFormat.getInstance(Locale.GERMANY);
        if (Math.abs(bytes) < 1024) {
            return bytes + " B";
        }
        if (Math.abs(bytes) >= 1024 * 1024) {
            float megaBytes = (float) bytes / (1024 * 1024);
            return nf.format(megaBytes) + " MB";
        }
        float kiloBytes = (float) bytes / 1024;

        return nf.format(kiloBytes) + " KB";
    }
}

Related

  1. getReadableSize(long size)
  2. getSize(long octets)
  3. getSizeAll(final long bytes)
  4. getSizeFormat()
  5. getSizeInKB(String size)
  6. getSizeString(long number, Locale locale)
  7. getSizeString(long size)
  8. getSizeText(long size)
  9. getSpaceSizeFromByte(long xB)