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

How to Post an Empty Body to REST API via HttpClient in C When working with REST APIs in C#, you may come across scenarios where you need to send a POST request with an empty body. This can be useful in situations where the API endpoint expects a POST request but doesn’t require any ...

Read more

Does C# have IsNullOrEmpty for List/IEnumerable?

If you’ve been working with C# for a while, you may have come across situations where you need to check if a List or IEnumerable is null or empty. In some other languages, like JavaScript, you have the convenience of using the Array.isArray() method or the length property to check if an array is empty ...

Read more

List Queries: 20 Times Faster than IQueryable?

Have you ever wondered why list queries are often faster than IQueryable queries in C#? In this article, we will explore the reasons behind this performance difference and discuss when and how to use each type of query. What is IQueryable? Before we dive into the performance comparison, let’s first understand what IQueryable is. IQueryable ...

Read more

Passing Different Number of Arguments to a Params Method at Runtime

How to Pass a Different Number of Arguments Using a List and Converting to an Array One way to pass a different number of arguments to a params method at runtime is by using a List<object> to store the arguments and then converting it to an array using the ToArray() method. Here’s an example: List<object> ...

Read more

Leave a Comment