DEV Community

Cover image for Numerical Alchemy: Converting Numbers to Text in C#
Bala Madhusoodhanan
Bala Madhusoodhanan

Posted on

1 1 1 1 1

Numerical Alchemy: Converting Numbers to Text in C#

Intro:
I find immense joy in exploring the endless possibilities that code plugins offer. Recently one of the problem that was requested to be solved was to convert numbers to text. Some of the scenarios where this would be super useful with business process would be

  • Financial Documents: Writing out numbers in words on checks, invoices, and contracts to prevent fraud and ensure clarity.

  • Legal Documents: Ensuring precision in legal agreements and documents where numbers need to be clearly understood.
    Educational Tools: Helping young children learn numbers and their corresponding words.

  • Data Entry: Reducing errors in data entry by providing both numerical and textual representations.

Custom Code plugin for custom connector:

using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

public class Script : ScriptBase
{
    public override async Task<HttpResponseMessage> ExecuteAsync()
    {
        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);

        // Read the request content
        string requestBody = await this.Context.Request.Content.ReadAsStringAsync();
        JObject json = JObject.Parse(requestBody);
        int number = (int)json["num"];

        // Convert the number to words
        string numberInWords = NumberToWords(number);

        // Create the JSON response
        response.Content = CreateJsonContent($"{{\"message\": \"{numberInWords}\"}}");
        return response;
    }

    private static string[] units = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
    private static string[] teens = { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
    private static string[] tens = { "", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
    private static string[] thousands = { "", "Thousand", "Million", "Billion" };

private static string NumberToWords(int number)
{
    if (number == 0)
        return "Zero";

    if (number < 0)
        return "Minus " + NumberToWords(Math.Abs(number));

    string words = "";

    int[] numArray = new int[4];
    int first = 0;

    while (number > 0)
    {
        numArray[first++] = number % 1000;
        number /= 1000;
    }

    for (int i = first - 1; i >= 0; i--)
    {
        if (numArray[i] == 0)
            continue;

        string segment = "";

        int u = numArray[i] % 10;
        int t = (numArray[i] / 10) % 10;
        int h = (numArray[i] / 100) % 10;

        if (h > 0)
            segment += units[h] + " Hundred ";

        if (t > 0)
        {
            if (t == 1)
            {
                segment += teens[u] + " ";
            }
            else
            {
                segment += tens[t] + " ";
                if (u > 0)
                    segment += units[u] + " ";
            }
        }
        else if (u > 0)
        {
            segment += units[u] + " ";
        }

        if (segment != "")
            words += segment + thousands[i] + " ";
    }

    return words.Trim();
}
}
Enter fullscreen mode Exit fullscreen mode

Magic show:

demo1

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay