C#: Convert number into word

I have a commercial web system which generates invoices and prints them.

The printed invoice must have the TOTAL AMOUNT, in numbers and in letters.

For example:

S/. 945.23 = NOVECIENTOS CUARENTA Y CINCO CON 23/100 NUEVOS SOLES (spanish)

I had done an algorithm for this about 10 years ago when I was at university, so I had some idea.

However, I found this excellent post on the subject:

Converting Numbers to Words by Jonathan Wood

I did some changes to this solution because I need numbers written in spanish letters.

Here it is:

using System;
using System.Text;

namespace MYPROJECT
{
static class NumberToText
{
private static string[] _ones =
{
"cero",
"un",
"dos",
"tres",
"cuatro",
"cinco",
"seis",
"siete",
"ocho",
"nueve"
};

private static string[] _teens =
{
"diez",
"once",
"doce",
"trece",
"catorce",
"quince",
"dieciseis",
"diecisiete",
"dieciocho",
"diecinueve"
};

private static string[] _tens =
{
"",
"diez",
"veinte",
"treinta",
"cuarenta",
"cincuenta",
"sesenta",
"setenta",
"ochenta",
"noventa"
};

private static string[] _centenas =
{
"",
"ciento",
"doscientos",
"trescientos",
"cuatrocientos",
"quinientos",
"seiscientos",
"setecientos",
"ochocientos",
"novecientos"
};

private static string[] _thousands =
{
"",
"mil",
"millon",
"billon",
"trillon",
"cuatrillon"
};

/// <summary>
/// Converts a numeric value to words suitable for the portion of
/// a check that writes out the amount.
/// </summary>
/// <param name="value">Value to be converted</param>
/// <returns></returns>
public static string Convert(decimal value)
{
string digits, temp;
bool showThousands = false;
bool allZeros = true;

// Use StringBuilder to build result
StringBuilder builder = new StringBuilder();
// Convert integer portion of value to string
digits = ((long)value).ToString();
// Traverse characters in reverse order
for (int i = digits.Length - 1; i >= 0; i--)
{
int ndigit = (int)(digits[i] - '0');
int column = (digits.Length - (i + 1));

// Determine if ones, tens, or hundreds column
switch (column % 3)
{
case 0:        // Ones position
showThousands = true;
if (i == 0)
{
// First digit in number (last in loop)
temp = String.Format("{0} ", _ones[ndigit]);
}
else if (digits[i - 1] == '1')
{
// This digit is part of "teen" value
temp = String.Format("{0} ", _teens[ndigit]);
// Skip tens position
i--;
}
else if (ndigit != 0)
{
// Any non-zero digit
//if (column == 0)
//{
temp = String.Format("{0} ", _ones[ndigit]);
//}
//else
//{
//    temp = String.Format("{0} ", ndigit == 1 ? "un" : _ones[ndigit]);
//}
}
else
{
// This digit is zero. If digit in tens and hundreds
// column are also zero, don't show "thousands"
temp = String.Empty;
// Test for non-zero digit in this grouping
if (digits[i - 1] != '0' || (i > 1 && digits[i - 2] != '0'))
showThousands = true;
else
showThousands = false;
}

// Show "thousands" if non-zero in grouping
if (showThousands)
{
if (column > 0)
{
temp = String.Format("{0}{1}{2}",
temp,
_thousands[column / 3],
allZeros ? " " : ", ");
}
// Indicate non-zero digit encountered
allZeros = false;
}
builder.Insert(0, temp);
break;

case 1:        // Tens column
if (ndigit > 0)
{
temp = String.Format("{0}{1}",
_tens[ndigit],
(digits[i + 1] != '0') ? " y " : " ");
builder.Insert(0, temp);
}
break;

case 2:        // Hundreds column
if (ndigit > 0)
{
temp = String.Format("{0} ", _centenas[ndigit]);
builder.Insert(0, temp);
}
break;
}
}

// Append fractional portion/cents
builder.AppendFormat("con {0:00}/100", (value - (long)value) * 100);

// Capitalize first letter
return String.Format("{0}{1}",
Char.ToUpper(builder[0]),
builder.ToString(1, builder.Length - 1));
}
}
}

References:

3 responses to this post.

  1. We hope clash of clans hack that you like this
    hack, and we only have 46, 000. Second – Don’t Upgrade your town hall you open yourself
    up to many more defenses, but if you wish to unlock this character your dark barracks will have to
    purchase it from the incorrect one. Search them up online and you can
    come across Clash of Clans Hack Tool Features – Add unlimited GemsStep 4.
    Now comes the hard part.

    Responder

  2. Posted by PhuongTran on 25 agosto, 2014 at 2:20

    Hi Nathan,

    This article is really helpful for me. I am looking for a function to convert amount to text in Spanish. however, there are some difference between your source code and google translate. I have confused and I don’t know which text is correct for amount value in some cases.

    Ex:

    1. one dollar
    2. fourty one dollars
    3. fifty one dollars
    4. one hundred one dollars
    5. one thousand dollars
    6. one thousand one dollars
    7. one thousand fourty one dollars
    8. one thousand one hundred forty one dollars
    9. one hundred thousand dollars
    10. one hundred one thousand dollars
    11. one hundred thousand one hundred dollars

    Google translate:

    1. un dólar
    2. cuarenta y un dólares
    3. cincuenta y un dólares
    4. ciento uno dólares
    5. mil dólares
    6. mil y un dólares
    7. mil cuarenta y un dólares
    8. un mil ciento cuarenta y un dólares
    9. cien mil dólares
    10. ciento un mil dólares
    11. cien mil cien dólares

    The result after running your source code:
    1. Un con 00/100
    2. Cuarenta y un con 00/100
    3. Cincuenta y un con 00/100
    4. Ciento un con 00/100
    5. Un mil con 00/100
    6. Un mil, un con 00/100
    7. Un mil, cuarenta y un con 00/100
    8. Un mil, ciento cuarenta y un con 00/100
    9. Ciento mil con 00/100
    10. Ciento un mil con 00/100
    11. Ciento mil, ciento con 00/100

    Pls!

    Responder

  3. Posted by Guaroa on 13 septiembre, 2015 at 18:15

    Very helpful for me, im from Dominican Republic. My name is Guaroa Mendez, you canc check me in facebook. Regards.

    Responder

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s

A %d blogueros les gusta esto: