Java Number Format Pattern formatBitRate(long bytes)

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

Description

Returns human readable bit rate, to be displayed as a label.

License

Apache License

Parameter

Parameter Description
bytes bytes per second

Return

formatted bits per second

Declaration

public static String formatBitRate(long bytes) 

Method Source Code

//package com.java2s;
/*//from   w  w w  .j a  v a 2s .  c om
 * Copyright 2015 Open Networking Laboratory
 *
 * 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 double KILO = 1024;
    public static final double MEGA = 1024 * KILO;
    public static final double GIGA = 1024 * MEGA;
    public static final String GBITS_UNIT = "Gb";
    public static final String MBITS_UNIT = "Mb";
    public static final String KBITS_UNIT = "Kb";
    public static final String BITS_UNIT = "b";
    private static final DecimalFormat DF2 = new DecimalFormat("#,###.##");
    private static final String SPACE = " ";
    private static final String PER_SEC = "ps";

    /**
     * Returns human readable bit rate, to be displayed as a label.
     *
     * @param bytes bytes per second
     * @return formatted bits per second
     */
    public static String formatBitRate(long bytes) {
        String unit;
        double value;

        //Convert to bits
        long bits = bytes * 8;
        if (bits > GIGA) {
            value = bits / GIGA;
            unit = GBITS_UNIT;

            // NOTE: temporary hack to clip rate at 10.0 Gbps
            //  Added for the CORD Fabric demo at ONS 2015
            // TODO: provide a more elegant solution to this issue
            if (value > 10.0) {
                value = 10.0;
            }

        } else if (bits > MEGA) {
            value = bits / MEGA;
            unit = MBITS_UNIT;
        } else if (bits > KILO) {
            value = bits / KILO;
            unit = KBITS_UNIT;
        } else {
            value = bits;
            unit = BITS_UNIT;
        }
        return DF2.format(value) + SPACE + unit + PER_SEC;
    }
}

Related

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