sabato 5 luglio 2025

C# convert dollar amount to letters

In questo frammento di codice, vedremo come nel linguaggio di programmazione C#, possiamo convertire un importo in lettere nella moneta dollari.

Di seguito si riporta la classe statica per la conversione dell'importo in lettere in lingua inglese.

C#

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Globalization;

 

 

namespace WinTestNet9

{

 

    public static class DollariInLettere

    {

 

     private static   string[] ones = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",   "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen",        "Eighteen", "Nineteen" };

 

        private static string[] tens = { "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };

 

        private static string[] thousands = { "", "Thousand", "Million", "Billion" };

      public  static string ConvertNumberToWords(decimal number)

        {

            if (number == 0)

                return "Zero Dollars";

 

            int intPart = (int)number;

 

            int decimalPart = (int)((number - intPart) * 100);

 

            string words = "";

 

            int thousandCounter = 0;

 

            while (intPart > 0)

            {

                if (intPart % 1000 != 0)

                {

                    words = ConvertHundreds(intPart % 1000) +    thousands[thousandCounter] + " " + words;

                }

                intPart /= 1000;

                thousandCounter++;

            }

 

            words = words.Trim();

 

             

            if (decimalPart > 0)

            {

                words += " and " + ConvertHundreds(decimalPart) + " Cents";

            }

 

            words += " Dollars";

            return words;

 

        }

     private   static string ConvertHundreds(int number)

        {

            string result = "";

            if (number >= 100)

            {

                result += ones[number / 100] + " Hundred ";

                number %= 100;

            }

 

            if (number >= 20)

            {

                result += tens[number / 10] + " ";

                number %= 10;

            }

 

 

            if (number > 0)

            {

                result += ones[number] + " ";

            }

 

            return result.Trim();

 

        }

 

 

 

    }

}


Di seguito si riporta il relativo utilizzo

C#

private void convertiNumeriInLettere(string numero = "")

 {

 

      

     string testoDollari = DollariInLettere.ConvertNumberToWords(decimal.Parse(numero));

     string testoConvertito = Euro

 

 

 }




L'importo "1876,45" verrà tradotto in "OneThousand Eight Hundred Seventy Six and Forty Five Cents Dollars"

Nessun commento: