01.Blogs :
mauriciogonzatto  
.NET, C#, Oracle, Web, tecnologia em geral e diversidades.

Número por extenso :: C#

:p Tava de brincadeira aqui e resolvi fazer uma classe pra escrever número por extenso em C#;

    ///<summary>
    /// Classe para retorno de valor por extenso do número
    /// MRG
    ///<summary>
    public class Extenso
    {
        protected string _nroExtenso = "";
        protected string _Nro;

        // Inicia processo de escrita do número
        // retorna número por extenso
        public string NumeroExtenso( string param1 ){

            this._Nro = param1;
            this._Nro = this._Nro.Replace(".","");
            string[] split = this._Nro.Split(',');

            for( int i = 0; i < split.Length; i++ ){
                int numero = 0;

                try{
                    numero = Convert.ToInt32( split[i] );
                    if(numero < 0){
                        this._nroExtenso += "MENOS ";
                        numero = Convert.ToInt32( numero.ToString().Replace("-","") );
                    }
                }
                catch{
                    throw new Exception("Número deve ser menor que 999999999");
                }

                this._nroExtenso += (i==split.Length-1 && split.Length > 1 ? " E " : " ");

                switch( numero.ToString().Length ){
                    // Unidade
                    case 1 :
                        this._nroExtenso += this.Unidades( numero );
                        break;
                    // Dezena
                    case 2 :
                        this._nroExtenso += this.Dezenas( numero );
                        break;
                    // Centena
                    case 3 :
                        this._nroExtenso += this.Centenas( numero );
                        break;
                    // Milhar
                    case 4 :
                        this._nroExtenso += this.Milhar( numero, 2 );
                        break;
                    case 5 :
                        this._nroExtenso += this.Milhar( numero, 2 );
                        break;
                    case 6 :
                        this._nroExtenso += this.Milhar( numero, 2 );
                        break;
                    // Milhão
                    case 7 :
                        this._nroExtenso += this.Milhar( numero, 3 );
                        break;
                    case 8 :
                        this._nroExtenso += this.Milhar( numero, 3 );
                        break;
                    case 9 :
                        this._nroExtenso += this.Milhar( numero, 3 );
                        break;
                    // Bilhão
                    case 10 :
                        this._nroExtenso += this.Milhar( numero, 4 );
                        break;
                    case 11 :
                        this._nroExtenso += this.Milhar( numero, 4 );
                        break;
                    case 12 :
                        this._nroExtenso += this.Milhar( numero, 4 );
                        break;
                }
                this._nroExtenso += (i==split.Length-1 && split.Length > 1 ? " DÉCIMOS" : " ");
            }
            return this._nroExtenso;
        }


        /// <Summary>
        /// Retorna valor por escrito de unidades
        /// </Summary>
        protected string Unidades( int param1 ){
            string[] _arrUnidade = new string[] {"ZERO","UM","DOIS","TRÊS",
                                                 "QUATRO","CINCO","SEIS",
                                                 "SETE","OITO","NOVE"};
            return _arrUnidade[param1];
        }


        /// <Summary>
        /// Retorna valor por escrito de dezenas
        /// </Summary>
        protected string Dezenas( int param1 ){
            string[] _arrDezena = new string[]{"DEZ","ONZE","DOZE","TREZE",
                                               "QUATORZE","QUINZE","DEZESSEIS",
                                               "DEZESSETE","DEZOITO","DEZENOVE",
                                               "VINTE","TRINTA","QUARENTA",
                                               "CINQUENTA","SESSENTA","SETENTA",
                                               "OITENTA","NOVENTA"};
            string retorno = null;
            if( param1.ToString().Length == 2 ){
                //Quebra string em array de 2 índices
                int[] _arrInt = new int[]{ Convert.ToInt32( param1.ToString().Substring(0,1) ),
                                           Convert.ToInt32( param1.ToString().Substring(1,1) ) };
                // Se for de 2 caracteres e o primeiro for == 0 é unidade :D
                if( _arrInt[0] == 0 ){
                    retorno = this.Unidades( _arrInt[1] );
                }else{ // Senão é dezena :p
                    if( param1 > 9 && param1 < 21 ){
                        if( param1 != 20 ){
                            retorno = _arrDezena[ _arrInt[1] ];
                        }else{
                            retorno = _arrDezena[10];
                        }
                    }else{
                        int j = 30;
                        int z = 10;
                        for( int i=20; i <= 100; i += 10, j = i+10 ){
                            if( ( param1 > i ) && ( param1 < (j+1) ) ){
                                if( param1 != j ){
                                    retorno = _arrDezena[z] + " E " + this.Unidades( _arrInt[1] );
                                    break;
                                }else{
                                    retorno = _arrDezena[z+1];
                                    break;
                                }
                            }
                            z++;
                        }
                    }
                }
            }else{
                retorno = this.Unidades( param1 );
            }
            return retorno;
        }

        ///<Summary>
        ///    Retorna valor por escrita de Centena
        ///</Summary>
        protected string Centenas( int param1 ){
            string[] _arrCentena = new string[]{"CENTO","DUZENTOS","TREZENTOS",
                                                "QUAROCENTOS","QUINHENTOS",
                                                "SEISSENTOS","SETESSENTOS",
                                                "OITOCENTOS","NOVESSENTOS"};
            string retorno = null;
            if( param1.ToString().Length == 3 ){
                int[] _arrInt = new int[]{ Convert.ToInt32( param1.ToString().Substring(0,1) ),
                                           Convert.ToInt32( param1.ToString().Substring(1,1) ),
                                           Convert.ToInt32( param1.ToString().Substring(2,1) ) };
                int _dezena = Convert.ToInt32( _arrInt[1].ToString() + _arrInt[2].ToString() );
                if( _arrInt[0] == 0 ){
                    if( _arrInt[1] == 0 ){
                       retorno = this.Unidades( _arrInt[2] );
                    }else{
                       retorno = this.Dezenas( _dezena );
                    }
                }else{
                    int j = 200;
                    int z = 0;
                    for( int i=100; i <= 1000; i += 100, j = i+100 ){
                        if( ( param1 > i ) && ( param1 < (j+1) ) ){
                            if( param1 != j ){
                                retorno = _arrCentena[z] + " E " +
                                    ( _dezena > 10 ? this.Dezenas( _dezena ) : this.Unidades( _dezena ) );
                                break;
                            }else{
                                retorno = _arrCentena[z+1];
                                break;
                            }
                        }else if( param1 == 100 ){
                            retorno = "CEM";
                            break;
                        }
                        z++;
                    }
                }
            }else{
                retorno = this.Dezenas( param1 );
            }
            return retorno;
        }

        ///<Summary>
        /// Mil
        ///</Summary>
        protected string Milhar( int param1, int aux ){

            string retorno = "";
            string[] lista = new string[aux];
            int j= 0;
            int resto;
            int z = aux;

            for( int i = 1; i <= aux; i++ ){

                resto = param1.ToString().Length%3;

                if( i == 1 ){
                    lista[i-1] =
                        (param1.ToString().Length%3) == 0 ? param1.ToString().Substring(j,3) :
                         param1.ToString().Substring(j, param1.ToString().Length%3);
                }else{
                    lista[i-1] = param1.ToString().Substring(j, 3);
                }

                // Verifica o length do último valor inserido na matriz
                // para incrementar j e acançar no laço for
                switch( lista[i-1].Length ){
                    case 1 :
                        retorno += this.Unidades( Convert.ToInt32( lista[i-1] ) );
                        j += 1;
                        break;
                    case 2 :
                        retorno += this.Dezenas( Convert.ToInt32( lista[i-1] ) );
                        j += 2;
                        break;
                    case 3 :
                        retorno += this.Centenas( Convert.ToInt32( lista[i-1] ) );
                        j += 3;
                        break;
                }

                // Verifica z e checa se é mil, milhão, bilhão : singular ou plural
                switch( z ){
                    case 2 :
                        retorno += " MIL ";
                        break;
                    case 3 :
                        retorno +=  ( Convert.ToInt32(lista[i-1]) > 1 ? " MILHÕES " : " MILHÃO " );
                        break;
                    case 4 :
                        retorno +=  ( Convert.ToInt32(lista[i-1]) > 1 ? " BILHÕES " : " BILHÃO " );
                        break;
                }

                if(z != 1){ retorno += " "; }
                z--;
            }
            return retorno;
        }
    }

Críticas, dúvidas ou sugestões....estamos ae!

[]'s

posted on Friday, March 03, 2006 6:46 AM by mauriciogonzatto

# re: N&#250;mero por extenso :: C# @ Friday, March 03, 2006 4:53 PM

Boa dica...

juliano_netfox

# Verifique essa @ Friday, March 03, 2006 5:50 PM

Tem uma rotina super simples neste link, de uma olhada, embora esteja em VFP pode econimizar muito código:

http://www.foxbrasil.com.br/forum/viewtopic.php?t=98

VFP

# re: N&#250;mero por extenso :: C# @ Friday, March 03, 2006 8:15 PM

Quando 1000 retorna: UM MIL ZERO.
Unica falha que observei...

[]s Juliano

julianocarvalho

# re: N&#250;mero por extenso :: C# @ Saturday, March 04, 2006 8:39 AM

Valew Juliano!

VFP, vou veririficar a sugestão!

Obrigado!

[]'s

mauriciogonzatto


 
03.UPDATE CALENDAR :
<March 2006>
SunMonTueWedThuFriSat
2627281234
567891011
12131415161718
19202122232425
2627282930311
2345678

05.MY LINKS :

07.Subscriptions :

Subscriptions


© Copyright 2005 Microsoft Corporation. All Rights Reserved.
Terms of Use | Privacy Statement | Code of Conduct | Hosted by MaximumASP for Microsoft
WHO-BAR