Here you can find the source of getFormatSizeByKB(long size)
public static String getFormatSizeByKB(long size)
//package com.java2s; /*/*from www. ja va 2 s . c om*/ * Copyright 2015 lixiaobo * * VersionUpgrade project 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.math.BigDecimal; public class Main { public static String getFormatSizeByKB(long size) { double kiloByte = size / 1024; if (kiloByte < 1) { return size + "KB"; } double megaByte = kiloByte / 1024; if (megaByte < 1) { BigDecimal result1 = new BigDecimal(Double.toString(kiloByte)); return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB"; } double gigaByte = megaByte / 1024; if (gigaByte < 1) { BigDecimal result2 = new BigDecimal(Double.toString(megaByte)); return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB"; } BigDecimal result4 = new BigDecimal(gigaByte); return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB"; } }