venerdì 9 maggio 2025

C# convertire un importo di tipo dollari in lettere

Di seguito si riporta una classe che permette di convertire un importo di tipo dollari, in testo inglese.
In particolare dato un importo, scrive in lingue inglese il testo di tale importo.


Di seguito la classe nel linguaggio C# per convertire un importo in testo inglese per dollari.

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();

 

        }

 

 

 

    }

}

 




Qui di seguito il relativo utilizzo.

C#

private void convertiNumeriInLettere(string numero = "")

 {

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

     string testoConvertito = Euro


 }


Per il valore "1874,45",  verrà restituito il seguente testo "OneThousand Eight Hundred Seventy Four and Forty Five Cents Dollars".

Nessun commento:

Posta un commento