Java Number Format formatPattern(String number, String pattern)

Here you can find the source of formatPattern(String number, String pattern)

Description

format Pattern

License

Open Source License

Declaration

public static String formatPattern(String number, String pattern) 

Method Source Code

//package com.java2s;
/**//w  w w  . j  a  v a2  s  .c om
 * $RCSfile: ,v $
 * $Revision: $
 * $Date: $
 * 
 * Copyright (C) 2004-2011 Jive Software. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    public static String formatPattern(String number, String pattern) {

        StringBuffer str = new StringBuffer();
        number = removeInvalidChars(number);

        for (int i = 0, j = 0; i < number.length(); j++) {
            if (j < pattern.length()) {
                char c = pattern.charAt(j);
                if (c == 'x' || c == 'X')
                    str.append(number.charAt(i++));
                else
                    str.append(c);
            } else {
                str.append(number.charAt(i++));
            }
        }

        return str.toString();
    }

    public static String removeInvalidChars(String number) {
        if (number == null) {
            return null;
        }

        for (String str : new String[] { "-", "(", ")", " ", "+", "[", "]" })
            number = number.replace(str, "");

        return number;
    }
}

Related

  1. formatNumberWithKSeparators(int value)
  2. formatNumberWithSameWidth(int d)
  3. formatOnlyLettersNumbersAndSpaces(String keyword)
  4. formatPaddedNumber(long number, int numericPadding)
  5. formatPartialName(String name, int numberOfCharacters)
  6. formatPct(final Number amount)
  7. formatPercentage(Number numerator, Number denominator)
  8. formatPhone(String phoneNumber, String formattingPattern, String countryCode)
  9. formatPhoneNo(String country, String area, String number, String inline)