Java Number Format Pattern formatBytes(long numBytes)

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

Description

format Bytes

License

Apache License

Declaration

public static String formatBytes(long numBytes) 

Method Source Code

//package com.java2s;
/**//  ww  w . ja v  a  2s.com
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 {
    final static long KB = 1024L * 1;
    final static long MB = 1024L * KB;
    final static long GB = 1024L * MB;
    final static long TB = 1024L * GB;
    final static long PB = 1024L * TB;
    static DecimalFormat dfm = new DecimalFormat("####.000");
    static DecimalFormat ifm = new DecimalFormat("###,###,###,###,###");

    public static String formatBytes(long numBytes) {
        StringBuffer buf = new StringBuffer();
        boolean bDetails = true;
        double num = numBytes;

        if (numBytes < KB) {
            buf.append(numBytes + " B");
            bDetails = false;
        } else if (numBytes < MB) {
            buf.append(dfmt(num / KB) + " KB");
        } else if (numBytes < GB) {
            buf.append(dfmt(num / MB) + " MB");
        } else if (numBytes < TB) {
            buf.append(dfmt(num / GB) + " GB");
        } else if (numBytes < PB) {
            buf.append(dfmt(num / TB) + " TB");
        } else {
            buf.append(dfmt(num / PB) + " PB");
        }
        if (bDetails) {
            buf.append(" (" + ifmt(numBytes) + " bytes)");
        }
        return buf.toString();
    }

    public static String dfmt(double d) {
        return dfm.format(d);
    }

    public static String ifmt(double d) {
        return ifm.format(d);
    }
}

Related

  1. formatBitRate(long bytes)
  2. formatBytes(long bytes)
  3. formatBytes(long bytes)
  4. formatBytes(long bytes)
  5. formatBytes(long bytes)
  6. formatDashboardNumber(Number amount)
  7. formatDisplay(String displayString)
  8. formatDollar(Object obj)
  9. formatDollarTd(Object obj)