Java Percentage Format percentage(float f)

Here you can find the source of percentage(float f)

Description

f should be in the range 0 - 1

License

Open Source License

Declaration

public static String percentage(float f) 

Method Source Code

//package com.java2s;
/*/*  ww w .j  a  v a  2 s  .c  o  m*/
 * Robonobo Common Utils
 * Copyright (C) 2008 Will Morton (macavity@well.com) & Ray Hilton (ray@wirestorm.net)
    
 * This program 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 2
 * of the License, or (at your option) any later version.
    
 * This program 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
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

import java.text.NumberFormat;

public class Main {
    /**
     * f should be in the range 0 - 1
     */
    public static String percentage(float f) {
        if (f < 0f || f > 1f)
            throw new IllegalArgumentException();
        return padToMinWidth(f * 100, 3) + "%";
    }

    public static String padToMinWidth(double num, int minWidth) {
        NumberFormat nf = NumberFormat.getNumberInstance();
        int intDigits = numDigits((int) num);
        if (intDigits >= minWidth)
            nf.setMaximumFractionDigits(0);
        else {
            boolean hasFracComponent = (int) num != num;
            if (hasFracComponent) {
                nf.setMaximumFractionDigits(minWidth - intDigits);
                nf.setMinimumFractionDigits(minWidth - intDigits);
            }
        }
        return nf.format(num);
    }

    public static int numDigits(long val) {
        // This seems a bit ugly, there must be a more elegant way
        String s = String.valueOf(val);
        return s.length();
    }
}

Related

  1. getRoundPercent(double f)
  2. numberToPercent2Scale(Double number)
  3. percent(double number)
  4. percent(double p1, double p2)
  5. percentage(Double v, String postfix)
  6. percentageAsString(double input)
  7. percentageFormat(BigDecimal value)
  8. percentDecimalFormat(final double no)
  9. percentFormat()