Java Size Format formatStorageSize(Double size, String label)

Here you can find the source of formatStorageSize(Double size, String label)

Description

formatStorageSize Convert a double representation into the label of folder size.

License

Open Source License

Parameter

Parameter Description
size size of the file representation
label label for indiate the base is KB or MB

Return

String The String format after convertion

Declaration


public static String formatStorageSize(Double size, String label) 

Method Source Code

//package com.java2s;
/*//  w ww  .j  av a  2 s  .  c  o  m
 * @(#)TextUtility.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */

import java.text.NumberFormat;

public class Main {
    /**
    * formatStorageSize
    *
    * Convert a double representation into the label of folder size.
    *
    * @param    size      size of the file representation
    * @param    label     label for indiate the base is KB or MB
    * @return   String    The String format after convertion
    */

    public static String formatStorageSize(Double size, String label) {
        StringBuffer str = new StringBuffer();
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMaximumFractionDigits(2);
        nf.setMinimumFractionDigits(1);

        if (size != null) {
            if (("KB").equals(label)) {
                if (size.doubleValue() < 1024) {
                    str.append(nf.format(size.doubleValue())).append(" KB");
                } else if (size.doubleValue() < 1048576) {
                    str.append(nf.format(size.doubleValue() / 1024)).append(" MB");
                } else {
                    str.append(nf.format((size.doubleValue() / 1024.0) / 1024.0)).append(" GB");
                }
            } //end if kb
            else if (("MB").equals(label)) {
                if (size.doubleValue() >= 1024) {
                    str.append(nf.format(size.doubleValue() / 1024.0)).append(" GB");
                } else {
                    str.append(nf.format(size.doubleValue())).append(" MB");
                }
            } //end if label

        } //end if size!=null

        return str.toString();

    }
}

Related

  1. formatSize(long size)
  2. formatSize(long size, boolean forceFixLen, boolean forceSizeInBytes)
  3. formatSize(long sizeInByte)
  4. formatSize(long sizeInBytes)
  5. formatSizeInfo(long size)