How to Convert a Floating Point Number to Base36 in C#

Have you ever needed to convert a floating point number to Base36 in C#? If you’re familiar with JavaScript, you may have used the .toString(36) method to accomplish this. In C#, there is no built-in method for converting floating point numbers to Base36, but don’t worry, I’ve got you covered.

What is Base36?

Base36 is a numeral system that uses 36 different digits to represent numbers. It includes the digits 0-9 and the letters A-Z. This allows for a compact representation of numbers compared to other numeral systems like decimal (base 10) or binary (base 2).

How to Convert a Floating Point Number to Base36

To convert a floating point number to Base36 in C#, we can write our own converter using the following code:

public static class Base36Converter
{
    private const int Base = 36;
    private const string Chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static string ConvertTo(double value)
    {
        string result = "";

        // Handle negative numbers separately
        if (value < 0)
        {
            result += "-";
            value = Math.Abs(value);
        }

        // Extract the integer part of the number
        int intValue = (int)value;
        result += ConvertTo(intValue);

        // Extract the fractional part of the number
        double fractionalPart = value - intValue;

        // Convert the fractional part to Base36
        if (fractionalPart > 0)
        {
            result += ".";
            for (int i = 0; i < 10; i++)
            {
                fractionalPart *= Base;
                int digit = (int)fractionalPart;
                result += Chars[digit];
                fractionalPart -= digit;
            }
        }

        return result;
    }

    private static string ConvertTo(int value)
    {
        string result = "";

        while (value > 0)
        {
            result = Chars[value % Base] + result;
            value /= Base;
        }

        return result;
    }
}

Let’s break down the code step by step:

  1. We define a Base36Converter class with a private constant Base set to 36 and a constant Chars containing the digits and letters used in Base36.

  2. The ConvertTo method takes a double value as input and returns a string representation of the number in Base36. We start by initializing an empty string result.

  3. If the input value is negative, we append a “-” sign to the result and convert the absolute value of the number.

  4. We extract the integer part of the number using the int cast and append it to the result by calling the ConvertTo method.

  5. We calculate the fractional part of the number by subtracting the integer part from the original value.

  6. If the fractional part is greater than 0, we append a “.” to the result and convert the fractional part to Base36. We iterate 10 times to get 10 digits of precision.

  7. Inside the loop, we multiply the fractional part by the base and cast it to an int to get the next digit. We append the corresponding character from the Chars string to the result and subtract the digit from the fractional part.

  8. Finally, we return the result.

Example Usage

Let’s see an example of how to use the Base36Converter class:

double number = 1234.5678;
string base36Number = Base36Converter.ConvertTo(number);
Console.WriteLine(base36Number);

The output will be:

9IX.H5J8S4F3

Conclusion

Converting a floating point number to Base36 in C# is not as straightforward as it is in JavaScript, but with the Base36Converter class provided, you can easily accomplish this task. By following the steps outlined in this article, you can convert any floating point number to Base36 and use it in your C# applications.

Categories C#

Related Posts

C# Triple Double Quotes: What are they and how to use them?

In C# programming language, triple double quotes (“””) are a special syntax known as raw string literals. They provide a convenient way to work with strings that contain quotes or embedded language strings like JSON, XML, HTML, SQL, Regex, and others. Raw string literals eliminate the need for escaping characters, making it easier to write ...

Read more

Best Practices in Using a Lock in C#

What is a Lock? A lock in C# is implemented using the lock keyword, which ensures that only one thread can enter a specific section of code at a time. When a thread encounters a lock statement, it attempts to acquire a lock on the specified object. If the lock is already held by another ...

Read more

Usage of ‘&’ versus ‘&&’ in C#

‘&’ Operator The ‘&’ operator in C# is a bitwise AND operator. It operates at the bit level, meaning that it performs the AND operation on each corresponding pair of bits in the operands. This operator is commonly used when working with binary data or performing low-level bit manipulation. For example, consider the following code ...

Read more

How to Add a Badge to a C# WinForms Control

Have you ever wanted to add a badge to a C# WinForms control? Maybe you want to display a notification count on a button or indicate the status of a control. In this article, I will show you how to easily add a badge to a C# WinForms control using a static Adorner class. What ...

Read more

Leave a Comment