Java Integer Format formatInt(int value, int numDigit)

Here you can find the source of formatInt(int value, int numDigit)

Description

Format an integer value with specifie integer digits number

License

Open Source License

Parameter

Parameter Description
value the value wich be formated
numDigit specifie the integer part size

Return

formated integer

Declaration

public static String formatInt(int value, int numDigit) 

Method Source Code

//package com.java2s;
/*/* w  ww.  ja v a 2 s. c  om*/
 * This file is part of org.kalmeo.util.
 * 
 * org.kalmeo.util 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 3 of the License, or
 * (at your option) any later version.
 * 
 * org.kalmeo.util 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 org.kalmeo.util.  If not, see <http://www.gnu.org/licenses/>.
 *  
 * Creation date : 17 janv. 08
 * Copyright (c) Kalmeo 2007-2008. All rights reserved.
 * http://www.kalmeo.org
 */

public class Main {
    /**
     * Format an integer value with specifie integer digits number
     * 
     * @param value the value wich be formated
     * @param numDigit specifie the integer part size
     * @return formated integer
     */
    public static String formatInt(int value, int numDigit) {
        if (numDigit == 0) {
            return "";
        }

        // First parse value to string
        String stringValue = Integer.toString(value);

        // numDigit lower than 0 imply no limit is fixed
        if (numDigit < 0) {
            return stringValue;
        }

        // Remove minus sign if value lower than 0
        int lengthValue = stringValue.length();
        boolean negative;
        if (negative = value < 0) {
            stringValue = stringValue.substring(1);
            lengthValue--;
        }

        // If stringValue's length greater than numDigit
        // return the numDigit later characters
        // Else complete with "0" characters
        if (lengthValue > numDigit) {
            stringValue = stringValue.substring(lengthValue - numDigit);
        } else {
            for (int i = lengthValue; i++ < numDigit; stringValue = "0" + stringValue)
                ;
        }

        // Return the value with is sign
        return (negative ? "-" : "") + stringValue;
    }
}

Related

  1. formatInt(int in, int precision)
  2. formatInt(int myint, int maxint)
  3. formatINT(int n)
  4. formatInt(int n)
  5. formatInt(int value, int length)
  6. formatInt(int value, int width)
  7. formatInt(String value)
  8. formatInt(String value)
  9. formatInt(String value, int defaultValue)