Here you can find the source of formatBinarySize(final long l)
Parameter | Description |
---|---|
l | a number, representing a binary size (e.g., memory); must be a power of 2. |
public static String formatBinarySize(final long l)
//package com.java2s; /* //from ww w . j a v a 2 s. com * DSI utilities * * Copyright (C) 2002-2009 Sebastiano Vigna * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library 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 Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ public class Main { /** A reasonable format for real numbers. */ private static final java.text.NumberFormat FORMAT_DOUBLE = new java.text.DecimalFormat("#,##0.00"); /** A reasonable format for integers. */ private static final java.text.NumberFormat FORMAT_LONG = new java.text.DecimalFormat("#,###"); /** Formats a binary size. * * <P>This method formats a long using suitable unit binary multipliers (e.g., <samp>Ki</samp>, <samp>Mi</samp>, <samp>Gi</samp>, and <samp>Ti</samp>) * and printing <em>no</em> fractional digits. The argument must be a power of 2. * @param l a number, representing a binary size (e.g., memory); must be a power of 2. * @return a string containing a pretty print of the number using binary unit multipliers. */ public static String formatBinarySize(final long l) { if ((l & -l) != l) throw new IllegalArgumentException("Not a power of 2: " + l); if (l >= (1L << 40)) return format(l >> 40) + "Ti"; if (l >= (1L << 30)) return format(l >> 30) + "Gi"; if (l >= (1L << 20)) return format(l >> 20) + "Mi"; if (l >= (1L << 10)) return format(l >> 10) + "Ki"; return Long.toString(l); } /** Formats a number. * * <P>This method formats a double separating thousands and printing just two fractional digits. * @param d a number. * @return a string containing a pretty print of the number. */ public static String format(final double d) { final StringBuffer s = new StringBuffer(); return FORMAT_DOUBLE.format(d, s, new java.text.FieldPosition(0)).toString(); } /** Formats a number. * * <P>This method formats a long separating thousands. * @param l a number. * @return a string containing a pretty print of the number. */ public static String format(final long l) { final StringBuffer s = new StringBuffer(); return FORMAT_LONG.format(l, s, new java.text.FieldPosition(0)).toString(); } }