Java tutorial
//package com.java2s; /** * CommonUtils.java created on 2014-07-14. * * Copyright (C) 2014 P1nGu1n * * This file is part of Snapshare. * * Snapshare is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Snapshare is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * a gazillion times. If not, see <http://www.gnu.org/licenses/>. */ public class Main { /** * Makes an human-readable string with 2 decimals of a number of bytes. * For example, (1024 * 1024 * 12.5) would return 12.50 MB. * @param bytes The number of bytes * @return The human-readable bytes */ public static String formatBytes(long bytes) { int exp = (int) (Math.log(bytes) / Math.log(1024)); String[] prefixes = new String[] { "", "K", "M", "G", "T", "P", "E" }; String prefix = prefixes[exp]; return String.format("%.2f %sB", bytes / Math.pow(1024, exp), prefix); } }