集册 Java实例教程 计算长值到可读大小

计算长值到可读大小

欢马劈雪     最近更新时间:2020-01-02 10:19:05

696
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
计算长值到可读大小

/*
nowjava.com - 时代Java 提供
*/

//package com.nowjava;

import java.math.BigDecimal;


public class Main {

    public static void main(String[] argv) {

        long longSize = 12312342;

        System.out.println(toStringSize(longSize));

    }


    public static final long SIZE_BT = 1024L;

    public static final long SIZE_KB = SIZE_BT * 1024L;

    public static final long SIZE_MB = SIZE_KB * 1024L;
    /*
     from n o w    j a v a  . c o m 
    */

    public static final long SIZE_GB = SIZE_MB * 1024L;

    public static final int SACLE = 2;


    public static String toStringSize(Long longSize) {

        if (longSize >= SIZE_BT && longSize < SIZE_KB) {

            return longSize / SIZE_BT + "KB";

        } else if (longSize >= SIZE_KB && longSize < SIZE_MB) {

            return longSize / SIZE_KB + "MB";

        } else if (longSize >= SIZE_MB && longSize < SIZE_GB) {

            BigDecimal longs = new BigDecimal(Double.valueOf(longSize + "")

                    .toString());

            BigDecimal sizeMB = new BigDecimal(Double.valueOf(SIZE_MB + "")

                    .toString());

            String result = longs.divide(sizeMB, SACLE,

                    BigDecimal.ROUND_HALF_UP).toString();

            return result + "GB";

        } else if (longSize >= SIZE_GB) {

            BigDecimal longs = new BigDecimal(Double.valueOf(longSize + "")

                    .toString());

            BigDecimal sizeMB = new BigDecimal(Double.valueOf(SIZE_GB + "")

                    .toString(
展开阅读全文