Java Number Format Pattern formatBytes(long bytes)

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

Description

Format a number of bytes into Megabytes/Kilobytes depending on the quantity.

License

Apache License

Parameter

Parameter Description
bytes The number of bytes.

Return

A human readable string.

Declaration

public static String formatBytes(long bytes) 

Method Source Code


//package com.java2s;
/*//from   w  w  w .  j a v a  2  s  .  com
 *  Copyright 2006 The National Library of New Zealand
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

import java.text.DecimalFormat;

public class Main {
    public static final DecimalFormat MEGABYTE_FORMAT = new DecimalFormat("#,###.00MB");
    public static final DecimalFormat KILOBYTE_FORMAT = new DecimalFormat("#,###.00KB");

    /**
     * Format a number of bytes into Megabytes/Kilobytes depending on the quantity.
     * @param bytes The number of bytes.
     * @return A human readable string.
     */
    public static String formatBytes(long bytes) {
        if (bytes > 1024 * 1024) {
            return MEGABYTE_FORMAT.format(((double) bytes) / (1024 * 1024));
        } else if (bytes > 1024) {
            return KILOBYTE_FORMAT.format(((double) bytes) / (1024));
        } else {
            return Long.toString(bytes) + "B";
        }
    }
}

Related

  1. format(String str_number, int digits)
  2. format(String value)
  3. formatAmtByComma(String amt, int len)
  4. formatBigNumber(long value)
  5. formatBitRate(long bytes)
  6. formatBytes(long bytes)
  7. formatBytes(long bytes)
  8. formatBytes(long bytes)
  9. formatBytes(long numBytes)