Java Swing Text Format formatCpfCNPJ(String str)

Here you can find the source of formatCpfCNPJ(String str)

Description

format Cpf CNPJ

License

Open Source License

Declaration

public static String formatCpfCNPJ(String str) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.text.ParseException;

import javax.swing.text.MaskFormatter;

public class Main {
    public static String formatCpfCNPJ(String str) {

        str = str.replaceAll("[\\D]", "");

        String pattern;//from   w w  w  . j  a v a  2s .  c o m
        if (str.length() <= 11) {
            str = String.format("%011d", Long.parseLong(str));
            pattern = "###.###.###-##";
        } else {
            str = String.format("%014d", Long.parseLong(str));
            pattern = "##.###.###/####-##";
        }

        try {
            MaskFormatter mask = new MaskFormatter(pattern);
            mask.setValueContainsLiteralCharacters(false);
            return mask.valueToString(str);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. formata(String s, String mascara)
  2. formatAreaImperial(BigDecimal areaDec)
  3. formatAreaMetric(BigDecimal area)
  4. formatCEP(String str)
  5. formatCpfCnpj(String cpfCnpj)
  6. formatNumericString(String string, String mask)
  7. getBidiVisualPosition(final int start, final int end, final Element neighbouringElement, final int pos, final Position.Bias b0, final Position.Bias[] biasRet, final int length, final boolean toWest, final boolean isLTR)
  8. getElementByPosition(final Element rootElement, final int pos)
  9. getElementIndex(Element elem)