Java Decimal Format padToMinWidth(double num, int minWidth)

Here you can find the source of padToMinWidth(double num, int minWidth)

Description

pad To Min Width

License

Open Source License

Declaration

public static String padToMinWidth(double num, int minWidth) 

Method Source Code

//package com.java2s;
/*//from  w  w  w  .jav a  2  s  . c  om
 * 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 {
    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. Julian_Cal(double JDN)
  2. listToString(List list)
  3. numToString(double num)
  4. pad(double n)
  5. padding(final double number)
  6. prettyPrintLatLon(double coord, boolean isCoordKindLat)
  7. print(double[] y)
  8. printAlpha(double a[])
  9. printAngle(double angle)