Java File Size Readable Format toHuman(Double n)

Here you can find the source of toHuman(Double n)

Description

prints large numbers as KB, MB, GB or TB

License

Apache License

Parameter

Parameter Description
n the number to convert as string

Return

string representation of the number

Declaration

static public String toHuman(Double n) 

Method Source Code

//package com.java2s;
/*/*from w  w w.j a  v a2  s  .  c om*/
 * Copyright 2015 Lutz Fischer <lfischer at staffmail.ed.ac.uk>.
 *
 * 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.
 */

public class Main {
    /**
     * prints large numbers as KB, MB, GB or TB 
     * @param n the number to convert as string
     * @return string representation of the number
     */
    static public String toHuman(Double n) {
        if (n == null)
            return null;
        String u = "B";
        if (n > 1024) {
            n /= 1024;
            u = "KB";
        }
        if (n > 1024) {
            n /= 1024;
            u = "MB";
        }
        if (n > 1024) {
            n /= 1024;
            u = "GB";
        }
        if (n > 1024) {
            n /= 1024;
            u = "TB";
        }

        if (n > 10)
            return String.format("%.0f" + u, n);

        if (Math.abs(Math.round(n) - n) >= 0.1) {
            return String.format("%.1f" + u, n);
        }

        return String.format("%.0f" + u, n);
    }
}

Related

  1. getHumanSize(File dir)
  2. getReadableFileSize(int size)
  3. getReadableFileSize(long fileSizeInBytes)
  4. getReadableFileSize(long size)
  5. getReadableFileSize(long size, boolean abbreviation)
  6. toHumanReadableByteCount(final long bytes)
  7. toHumanReadableFileSize(long fileSize)
  8. toHumanReadableSize(final long bytes)