Convertir de Numero a letras.

15/07/2005 - 02:01 por Jorge | Informe spam
Alguien tandra algun script en C# que transforme un numero con decimales a
letras.
por ejemplo: 1673.34 = Mil Seicientos Setenta y tres - 34/100

Encontre algunos en español pero no funcionan.
El que encontre en ingles sirve pero no entiendo bien la conversion y no lo
he podido adaptar a español.

Preguntas similare

Leer las respuestas

#1 Eugenio Serrano [MVP]
15/07/2005 - 04:27 | Informe spam
Te paso un realizado por mi..

Saludos,
Eugenio Serrano
NDSoft Consultoría y Desarrollo
Microsoft MVP (ASP.Net)
http://spaces.msn.com/members/eugenioserrano/
http://tinyurl.com/63ybf



public class Utility

{

private readonly static string[] _numbersInWords = {

"uno",

"dos",

"tres",

"cuatro",

"cinco",

"seis",

"siete",

"ocho",

"nueve",

"diez",

"once",

"doce",

"trece",

"catorce",

"quince",

"dieciseis",

"diecisiete",

"dieciocho",

"diecinueve",

"veinte",

"veintiuno",

"veintidos",

"veintitres",

"veinticuatro",

"veinticinco",

"veintiseis",

"veintisiete",

"veintiocho",

"veintinueve",

"treinta",

"cuarenta",

"cincuenta",

"sesenta",

"setenta",

"ochenta",

"noventa",

"ciento",

"doscientos",

"trescientos",

"cuatrocientos",

"quinientos",

"seiscientos",

"setecientos",

"ochocientos",

"novecientos"};

private const string _centWord = "centavo(s)";

private const string _oneMillionWord = "un millon";

private const string _millionsWord = "millones";

private const string _oneThousandWord = "un mil";

private const string _thousandWord = "mil";

private const string _hundredWord = "cien";

private const string _oneHundredWord = "ciento un";

private const string _zeroWithWord = "cero con";

private const string _withWord = "con";

private const string _andWord = "y";

/// <summary>

/// Convert numbers to words

/// </summary>

/// <param name="Number"></param>

/// <returns></returns>

public static string NumberToWords(decimal Number)

{

StringBuilder Words;

string FormattedNumberString;

int decimalSeparatorLocation;

int millions;

int thousands;

int hundreds;

int decimals;

int ActualNumber = 0;

int c;

int d;

int u;

Words = new StringBuilder();

FormattedNumberString
Number.ToString("000000000.00");

char DecimalSeparator
Convert.ToChar((Convert.ToString(1.1)).Trim().Substring(1, 1));

decimalSeparatorLocation
FormattedNumberString.IndexOf(DecimalSeparator);

millions
Convert.ToInt32(FormattedNumberString.Substring(0,3));

thousands
Convert.ToInt32(FormattedNumberString.Substring(3,3));

hundreds
Convert.ToInt32(FormattedNumberString.Substring(6, 3));

decimals
Convert.ToInt32(FormattedNumberString.Substring(decimalSeparatorLocation+1,2

));

for (int NumberPart = 1; NumberPart <= 4;

NumberPart++)

{

switch (NumberPart)

{

case 1:

{

ActualNumber
millions;

if (millions == 1)

{


Words.Append(_oneMillionWord);


Words.Append(' ');

continue;

}

break;

}

case 2:

{

ActualNumber
thousands;

if (millions != 1 &&

millions != 0)

{


Words.Append(_millionsWord);


Words.Append(' ');

}

if (thousands == 1)

{


Words.Append(_oneThousandWord);


Words.Append(' ');

continue;

}

break;

}

case 3:

{

ActualNumber
hundreds;

if (thousands != 1

&& thousands != 0)

{


Words.Append(_thousandWord);


Words.Append(' ');

}

break;

}

case 4:

{

ActualNumber
decimals;

if (decimals != 0)

{

if (millions

== 0 && thousands == 0 && hundreds == 0)

{


Words.Append(_zeroWithWord);


Words.Append(' ');

}

else

{


Words.Append(_withWord);


Words.Append(' ');

}

}

break;

}

}

c = (int)(ActualNumber / 100);

d = (int)(ActualNumber - c * 100) / 10;

u = (int)(ActualNumber - (c * 100 + d * 10));

if (ActualNumber == 0) continue;

if (ActualNumber == 100)

{

Words.Append(_hundredWord);

Words.Append(' ');

continue;

}

else

{

if (ActualNumber == 101 &&

NumberPart != 3)

{


Words.Append(_oneHundredWord);

Words.Append(' ');

continue;

}

else

{

if (ActualNumber > 100)

{


Words.Append(_numbersInWords[c + 35]);

Words.Append(' ');

}

}

}

if (d < 3 && d != 0)

{

Words.Append(_numbersInWords[d * 10

+ u - 1]);

Words.Append(' ');

}

else

{

if (d > 2)

{


Words.Append(_numbersInWords[d + 26]);

Words.Append(' ');

if (u == 0)

{

continue;

}

Words.Append(_andWord);

Words.Append(' ');


Words.Append(_numbersInWords[u - 1]);

Words.Append(' ');

}

else

{

if (d == 0 && u != 0)

{


Words.Append(_numbersInWords[u - 1]);

Words.Append(' ');

}

}

}

}

if (decimals != 0)

{

Words.Append(_centWord);

}

// Resolve here particular problems.

Words.Replace("uno mil", "un mil");


return Words.ToString().Trim();

}

}






"Jorge" escribió en el mensaje
news:%237f%
Alguien tandra algun script en C# que transforme un numero con decimales a
letras.
por ejemplo: 1673.34 = Mil Seicientos Setenta y tres - 34/100

Encontre algunos en español pero no funcionan.
El que encontre en ingles sirve pero no entiendo bien la conversion y no
lo
he podido adaptar a español.


Respuesta Responder a este mensaje
#2 Julio Casal
16/07/2005 - 07:49 | Informe spam
Hola Jorge. Yo tengo una clase que me ha dado muy buenos resultados, pero
lamentablemente la tengo en VB.Net. De todas formas aquí la tienes por si te
es útil:

' ' ## Provee servicios para la conversión de números en palabras.
'
' Creada Por: Julio Casal
' Última Actualización: Julio 2, 2004
'
Imports System.Globalization

Public Class NumerosPalabras

#Region "Interfaz"
'## Enumera los posibles idiomas en los cuales se puede realizar la
transformación
Public Enum IdiomaTransformacion
Español
Ingles
End Enum


'******************************************************************************
'## Retorna la representación del número especificado en palabras.
'##PARAM numero Número a transformar.
'##PARAM nombreMoneda Nombre de la moneda.
'##PARAM idioma Idioma de la transformación.
'##RETURNS Representación del número especificado en palabras.

'******************************************************************************
Public Function TransformarNumeroEnPalabras(ByVal numero As Decimal,
ByVal nombreMoneda As String, ByVal idioma As IdiomaTransformacion) As String
Select Case idioma
Case IdiomaTransformacion.Español
Return TransformarNumeroEnPalabrasEspañol(numero,
nombreMoneda)
Case IdiomaTransformacion.Ingles
Return TransformarNumeroEnPalabrasIngles(numero, nombreMoneda)
End Select
End Function


'******************************************************************************
'## Retorna la representación del número especificado en palabras.
'##PARAM numero Número a transformar.
'##PARAM idioma Idioma de la transformación.
'##RETURNS Representación del número especificado en palabras.

'******************************************************************************
Public Function TransformarNumeroEnPalabras(ByVal numero As Decimal,
ByVal idioma As IdiomaTransformacion) As String
Select Case idioma
Case IdiomaTransformacion.Español
Return TransformarNumeroEnPalabrasEspañol(numero)
Case IdiomaTransformacion.Ingles
Return TransformarNumeroEnPalabrasIngles(numero)
End Select
End Function
#End Region

#Region "Transformación en Español"

'******************************************************************************
'## Retorna la representación del número especificado en palabras.
'##PARAM numero Número a transformar.
'##PARAM nombreMoneda Nombre de la moneda.
'##RETURNS Representación del número especificado en palabras.

'******************************************************************************
Private Function TransformarNumeroEnPalabrasEspañol(ByVal numero As
Decimal, _
ByVal nombreMoneda
As String) As String
Dim s As String
Dim DecimalPlace As Integer
Dim IntPart As String
Dim Cents As String

s = Format(Val(numero), "0.00")
DecimalPlace = InStr(s, _simboloDecimal)

If DecimalPlace <> 0 Then
IntPart = Left(s, DecimalPlace - 1)
Cents = Left(Mid(s, DecimalPlace + 1, 2), 2)
Else
IntPart = s
Cents = ""
End If

If IntPart = "0" Or IntPart = "" Then
s = "Cero "
ElseIf Len(IntPart) > 7 Then
s = IntNumToSpanish(CInt(Val(Left(IntPart, Len(IntPart) - 6))))
+ _
"Millones " + IntNumToSpanish(CInt(Val(Right(IntPart, 6))))
Else
s = IntNumToSpanish(CInt(Val(IntPart)))
End If

If nombreMoneda.Length > 0 Then
If Right(s, 9) = "Millones " Or Right(s, 7) = "Millón " Then
s = s + "de "
End If
Select Case s
Case "Un ", "Una "
s = s & Singular(nombreMoneda)
Case Else
s = s & nombreMoneda
End Select
End If

's = s & " "

If Val(Cents) > 0 Then
Cents = "con " + Cents + "/100"
Else
Cents = "con 00/100"
End If

Return (Trim(s + Cents)).ToUpper
End Function


'******************************************************************************
'## Retorna la representación del número especificado en palabras.
'##PARAM numero Número a transformar.
'##RETURNS Representación del número especificado en palabras.

'******************************************************************************
Private Function TransformarNumeroEnPalabrasEspañol(ByVal numero As
Decimal) As String
Return TransformarNumeroEnPalabrasEspañol(numero, String.Empty)
'Dim s As String
'Dim DecimalPlace As Integer
'Dim IntPart As String
'Dim Cents As String

's = Format(Val(numero), "0.00")
'DecimalPlace = InStr(s, _simboloDecimal)

'If DecimalPlace <> 0 Then
' IntPart = Left(s, DecimalPlace - 1)
' Cents = Left(Mid(s, DecimalPlace + 1, 2), 2)
'Else
' IntPart = s
' Cents = ""
'End If

'If IntPart = "0" Or IntPart = "" Then
' s = "Cero "
'ElseIf Len(IntPart) > 7 Then
' s = IntNumToSpanish(CInt(Val(Left(IntPart, Len(IntPart) - 6))))
+ _
' "Millones " + IntNumToSpanish(CInt(Val(Right(IntPart, 6))))
'Else
' s = IntNumToSpanish(CInt(Val(IntPart)))
'End If

'If Val(Cents) > 0 Then
' Cents = "con " + Cents + "/100"
'Else
' Cents = "con 0/100"
'End If

'Return (Trim(s + Cents)).ToUpper
End Function

Private Function IntNumToSpanish(ByVal numero As Integer) As String
Dim ptr As Integer
Dim n As Integer
Dim i As Integer
Dim s As String
Dim rtn As String
Dim tem As String

s = CStr(numero)
n = Len(s)

tem = ""
i = n
Do Until i = 0
tem = EvalPart(CInt(Val(Mid(s, n - i + 1, 1) + CStr(CloneChain(i
- 1, "0")))))
If Not tem = "Cero" Then
rtn = rtn + tem + " "
End If
i = i - 1
Loop

'//Filters
'//filterThousands
ReplaceAll(rtn, " Mil Mil", " Un Mil")
Do
ptr = InStr(rtn, "Mil ")
If ptr <> 0 Then
If InStr(ptr + 1, rtn, "Mil ") <> 0 Then
ReplaceStringFrom(rtn, "Mil ", "", ptr)
Else : Exit Do
End If
Else : Exit Do
End If
Loop

'//filterHundreds
ptr = 0
Do
ptr = InStr(ptr + 1, rtn, "Cien ")
If ptr <> 0 Then
tem = Left(Mid(rtn, ptr + 5), 1)
If tem = "M" Or tem = "" Then
Else
ReplaceStringFrom(rtn, "Cien", "Ciento", ptr)
End If
End If
Loop Until ptr = 0

'//filterMisc
ReplaceAll(rtn, "Diez Un", "Once")
ReplaceAll(rtn, "Diez Dos", "Doce")
ReplaceAll(rtn, "Diez Tres", "Trece")
ReplaceAll(rtn, "Diez Cuatro", "Catorce")
ReplaceAll(rtn, "Diez Cinco", "Quince")
ReplaceAll(rtn, "Diez Seis", "Dieciseis")
ReplaceAll(rtn, "Diez Siete", "Diecisiete")
ReplaceAll(rtn, "Diez Ocho", "Dieciocho")
ReplaceAll(rtn, "Diez Nueve", "Diecinueve")
ReplaceAll(rtn, "Veinte Un", "Veintiun")
ReplaceAll(rtn, "Veinte Dos", "Veintidos")
ReplaceAll(rtn, "Veinte Tres", "Veintitres")
ReplaceAll(rtn, "Veinte Cuatro", "Veinticuatro")
ReplaceAll(rtn, "Veinte Cinco", "Veinticinco")
ReplaceAll(rtn, "Veinte Seis", "Veintiseís")
ReplaceAll(rtn, "Veinte Siete", "Veintisiete")
ReplaceAll(rtn, "Veinte Ocho", "Veintiocho")
ReplaceAll(rtn, "Veinte Nueve", "Veintinueve")

'//filterOne
If Left(rtn, 1) = "M" Then
rtn = "Un " + rtn
End If
'//Un Mil...
If Left(rtn, 6) = "Un Mil" Then
rtn = Mid(rtn, 4)
End If

'//addAnd
For i = 65 To 88
If Not i = 77 Then
ReplaceAll(rtn, "a " + Chr(i), "* y " + Chr(i))
End If
Next
ReplaceAll(rtn, "*", "a")

IntNumToSpanish = rtn
End Function

Private Function EvalPart(ByVal x As Integer) As String
Dim rtn As String
Dim s As String
Dim i As Integer

Do
Select Case x
Case 0 : s = "Cero"
Case 1 : s = "Un"
Case 2 : s = "Dos"
Case 3 : s = "Tres"
Case 4 : s = "Cuatro"
Case 5 : s = "Cinco"
Case 6 : s = "Seis"
Case 7 : s = "Siete"
Case 8 : s = "Ocho"
Case 9 : s = "Nueve"
Case 10 : s = "Diez"
Case 20 : s = "Veinte"
Case 30 : s = "Treinta"
Case 40 : s = "Cuarenta"
Case 50 : s = "Cincuenta"
Case 60 : s = "Sesenta"
Case 70 : s = "Setenta"
Case 80 : s = "Ochenta"
Case 90 : s = "Noventa"
Case 100 : s = "Cien"
Case 200 : s = "Doscientos"
Case 300 : s = "Trescientos"
Case 400 : s = "Cuatrocientos"
Case 500 : s = "Quinientos"
Case 600 : s = "Seiscientos"
Case 700 : s = "Setecientos"
Case 800 : s = "Ochocientos"
Case 900 : s = "Novecientos"
Case 1000 : s = "Mil"
Case 1000000 : s = "Millón"
End Select

If s = "" Then
i = i + 1
x = CInt(x / 1000)
If x = 0 Then i = 0
Else
Exit Do
End If
Loop Until i = 0

rtn = s
Select Case i
Case 0 : s = ""
Case 1 : s = " Mil"
Case 2 : s = " Millones"
Case 3 : s = " Billones"
End Select

EvalPart = rtn + s
Exit Function

End Function

Private Sub ReplaceStringFrom( _
ByRef s As String, _
ByVal OldWrd As String, _
ByVal NewWrd As String, _
ByVal ptr As Integer)

s = Left(s, ptr - 1) + NewWrd + Mid(s, Len(OldWrd) + ptr)
End Sub

Private Function CloneChain(ByVal n As Integer, ByVal Chr As String) As
String
Dim i As Integer
Dim CharClone As String
Dim rtn As String

If Len(Chr) > 0 Then
CharClone = Mid(Chr, 1, 1)
For i = 1 To n
rtn = rtn + CharClone
Next
End If

Return rtn
End Function

Private Sub ReplaceAll( _
ByRef s As String, _
ByVal OldWrd As String, _
ByVal NewWrd As String)

Dim ptr As Integer
Do
ptr = InStr(s, OldWrd)
If ptr <> 0 Then
s = Left(s, ptr - 1) + NewWrd + Mid(s, Len(OldWrd) + ptr)
End If
Loop Until ptr = 0
End Sub
#End Region

#Region "Transformación en Inglés"
Private Function TransformarNumeroEnPalabrasIngles(ByVal numero As
Decimal) As String
Return TransformarNumeroEnPalabrasIngles(numero, String.Empty)
End Function

Private Function TransformarNumeroEnPalabrasIngles(ByVal numero As
Decimal, _
ByVal nombreMoneda As
String) As String

Dim s As String
Dim Temp As String
Dim IntPart As String
Dim Cents As String

Dim DecimalPlace, Count As Integer

Dim Place(9) As String
Place(2) = " Thousand "
Place(3) = " Million "
Place(4) = " Billion "
Place(5) = " Trillion "

'//Convert s to a string, trimming extra spaces.
s = Format(Val(numero), "0.00")
DecimalPlace = InStr(s, _simboloDecimal)

'//If we find decimal place...
If DecimalPlace > 0 Then
'//Convert cents
Temp = Left(Mid(s, DecimalPlace + 1) & "00", 2)
Cents = "And " & Integer.Parse(Temp).ToString & "/100"

'//Strip off cents from remainder to convert.
s = Trim(Left(s, DecimalPlace - 1))
End If

Count = 1
Do Until s = ""
'//Convert last 3 digits of s to English IntPart.
Temp = ConvertHundreds(Right(s, 3))
If Len(Temp) > 0 Then IntPart = Temp & Place(Count) & IntPart
If Len(s) > 3 Then
'//Remove last 3 converted digits from s.
s = Left(s, Len(s) - 3)
Else
s = ""
End If
Count = Count + 1
Loop

'//Clean up IntPart.
If nombreMoneda.Length > 0 Then
Select Case IntPart
Case ""
IntPart = "No " & nombreMoneda
Case "One"
IntPart = "One " & Singular(nombreMoneda)
Case Else
IntPart = IntPart & " " & nombreMoneda
End Select
End If

IntPart = IntPart & " "

Return (Trim(IntPart & Cents)).ToUpper
End Function

Private Function ConvertHundreds(ByVal MyNumber As String) As String
Dim rtn As String

'//Exit if there is nothing to convert.
If Val(MyNumber) = 0 Then Exit Function

'//Append leading zeros to number.
MyNumber = Right("000" & MyNumber, 3)

'//Do we have a hundreds place digit to convert?
If Not Left(MyNumber, 1) = "0" Then
rtn = ConvertDigit(Left(MyNumber, 1)) & " Hundred "
End If

'//Do we have a tens place digit to convert?
If Not Mid(MyNumber, 2, 1) = "0" Then
rtn = rtn & ConvertTens(Mid(MyNumber, 2))
Else
'//If not, then convert the ones place digit.
rtn = rtn & ConvertDigit(Mid(MyNumber, 3))
End If

ConvertHundreds = Trim(rtn)
End Function

Private Function ConvertTens(ByVal MyTens As String) As String
Dim rtn As String

'//Is value between 10 and 19?
If Val(Left(MyTens, 1)) = 1 Then
Select Case Val(MyTens)
Case 10 : rtn = "Ten"
Case 11 : rtn = "Eleven"
Case 12 : rtn = "Twelve"
Case 13 : rtn = "Thirteen"
Case 14 : rtn = "Fourteen"
Case 15 : rtn = "Fifteen"
Case 16 : rtn = "Sixteen"
Case 17 : rtn = "Seventeen"
Case 18 : rtn = "Eighteen"
Case 19 : rtn = "Nineteen"
Case Else
End Select
Else
'//.. otherwise it's between 20 and 99.
Select Case Val(Left(MyTens, 1))
Case 2 : rtn = "Twenty "
Case 3 : rtn = "Thirty "
Case 4 : rtn = "Forty "
Case 5 : rtn = "Fifty "
Case 6 : rtn = "Sixty "
Case 7 : rtn = "Seventy "
Case 8 : rtn = "Eighty "
Case 9 : rtn = "Ninety "
Case Else
End Select

'//Convert ones place digit.
rtn = rtn & ConvertDigit(Right(MyTens, 1))
End If

ConvertTens = rtn
End Function

Private Function ConvertDigit(ByVal MyDigit As String) As String
Select Case Val(MyDigit)
Case 1 : ConvertDigit = "One"
Case 2 : ConvertDigit = "Two"
Case 3 : ConvertDigit = "Three"
Case 4 : ConvertDigit = "Four"
Case 5 : ConvertDigit = "Five"
Case 6 : ConvertDigit = "Six"
Case 7 : ConvertDigit = "Seven"
Case 8 : ConvertDigit = "Eight"
Case 9 : ConvertDigit = "Nine"
Case Else : ConvertDigit = ""
End Select
End Function
#End Region

#Region "Utilerías Generales Internas"
Private _simboloDecimal As Char =
CChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator)

Private Function Singular(ByVal s As String) As String
If Len(s) >= 2 Then
If Right(s, 1) = "s" Then
If Right(s, 2) = "es" Then
Singular = Left(s, Len(s) - 2)
Else
Singular = Left(s, Len(s) - 1)
End If
Else
Singular = s
End If
End If
End Function
#End Region

End Class


Saludos.

Julio Casal
.Net Solution Developer
MCAD
Grupo Lebed


"Jorge" wrote:

Alguien tandra algun script en C# que transforme un numero con decimales a
letras.
por ejemplo: 1673.34 = Mil Seicientos Setenta y tres - 34/100

Encontre algunos en español pero no funcionan.
El que encontre en ingles sirve pero no entiendo bien la conversion y no lo
he podido adaptar a español.



email Siga el debate Respuesta Responder a este mensaje
Ads by Google
Help Hacer una preguntaRespuesta Tengo una respuesta
Search Busqueda sugerida