Display a number in bytes, kilobytes or megabytes. - Java java.lang

Java examples for java.lang:long Format

Description

Display a number in bytes, kilobytes or megabytes.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        long size = 42;
        System.out.println(fileSizeToString(size));
    }//from   w ww .ja  va 2  s  .com

    /**
     * Display a number in bytes, kilobytes or megabytes.
     *
     * @param size
     * @return File size in "pretty" format
     */
    public static String fileSizeToString(long size) {
        if (size >= (1024 * 1024) && size < (1024 * 1024 * 1024)) {
            return (size / 1024 / 1024) + "Mb";
        }
        if (size >= 1024 && size < (1024 * 1024)) {
            return (size / 1024) + "Kb";
        }
        return size + " bytes";
    }
}

Related Tutorials