Java Size Format formatBytes(long size)

Here you can find the source of formatBytes(long size)

Description

Displays the given in a human-readable format.

License

Open Source License

Parameter

Parameter Description
size a parameter

Return

The formatted string.

Declaration

public static String formatBytes(long size) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 *  Copyright (c) 2014 Mentor Graphics and others.
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  which accompanies this distribution, and is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 * /*from   w w w  .  java 2s  . c  o m*/
 *  Contributors:
 *     Mentor Graphics - initial API and implementation
 *******************************************************************************/

import java.text.DecimalFormat;

public class Main {
    /**
     * Displays the given in a human-readable format.
     * @param size
     * @return The formatted string.
     */
    public static String formatBytes(long size) {
        if (size <= 0) {
            return size + " B"; //$NON-NLS-1$
        }
        String[] units = new String[] { "B", "KB", "MB", "GB", "TB" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups]; //$NON-NLS-1$ //$NON-NLS-2$
    }
}

Related

  1. format(long size)
  2. formatBinarySize(final long l)
  3. formatBytes(double size)
  4. formatByteSize(long bytes)
  5. formatDataSize(final double dataSize)
  6. formatDataSize(long bytes)
  7. formatDecimal(double size)