Here you can find the source of formatByteSize(long bytes, int lastDigits)
Parameter | Description |
---|---|
bytes | number of bytes |
lastDigits | number of digits after the `.` point |
public static String formatByteSize(long bytes, int lastDigits)
//package com.java2s; /*/*w w w.j a va 2 s. com*/ * Created on 26.04.2005 * * Copyright 2005-2006 Daniel Jacobi * * 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 { /** * This methode formats the bytes in human readable form. With the * lastDigits you can specify the number of digits after the '.'. This is * turned off, if the value is less equal zero. * * @param bytes * number of bytes * @param lastDigits * number of digits after the `.` point * @return String representation of bytes */ public static String formatByteSize(long bytes, int lastDigits) { String formated = null; double work = bytes; long count = 0; // digits while (work >= 1024) { work /= 1024; count++; } formated = String.valueOf(work); // format last digits if (lastDigits > 0) { int pos = formated.lastIndexOf('.'); if (formated.length() - pos - 1 < lastDigits) { for (int i = formated.length() - pos - 1; i < lastDigits; i++) formated += "0"; } else { formated = formated.substring(0, pos + lastDigits + 1); } } // unit if (count == 0) { formated += " B"; } else if (count == 1) { formated += " kB"; } else if (count == 2) { formated += " MB"; } else if (count == 3) { formated += " GB"; } else if (count == 4) { formated += " TB"; } else if (count == 5) { formated += " PB"; } return formated; } }