How to convert a floating point number to Base36 in C# in the same way as JavaScript's .toString(36) does it
Asked Answered
P

4

5

I am trying to convert some code to the C# (from the JavaScript), I need to convert a double number(0.04036483168558814) to ".toString(36)/Base36" by C#.

JavaScript code here:

 var num = 0.04036483168558814;
 var n = num.toString(36);

Output(n) below :

0.1gb9f0lx08ij9wwfwkyk5d0a4i

I need this same above result by C#, so how I will get this same results in C# ??

I applied some code, but they are not working.. My code below(by C#) :

1)

string OutputVal = Convert.ToString(Int64.Parse("0.04036483168558814"), 36);

or

string OutputVal = Convert.ToString(Int64.Parse("0.04036483168558814".Substring(2)), 36);

2)

private const string CharList = "0123456789abcdefghijklmnopqrstuvwxyz";
        public static String Encode(long input)
        {
            if (input < 0) throw new ArgumentOutOfRangeException("input", input, "input cannot be negative");

            char[] clistarr = CharList.ToCharArray();
            var result = new Stack<char>();
            while (input != 0)
            {
                result.Push(clistarr[input % 36]);
                input /= 36;
            }
            return new string(result.ToArray());
        }

string OutputString = Encode(Int64.Parse("0.04036483168558814"));
or
string OutputString = Encode(Int64.Parse("0.04036483168558814".Substring(2)));
Phototelegraphy answered 16/11, 2015 at 6:9 Comment(1)
#924271Attired
R
6

According to MSDN, you can use Convert.ToString method in order to convert integer number to a string representation in base 2, 8, 10 or 16.

If you want to convert the number to a base 36, you can either use existing third-party libraries:

Check this CodeProject article or this GitHub project out.

Or you can write your own converter.
For example, this class converts integers to Base 36:

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

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

        while (value > 0)
        {
            result = Chars[value % Base] + result; // use StringBuilder for better performance
            value /= Base;
        }

        return result;
    }
}

Note that result will be in big-endian order.
For example, decimal 1296 will be 100 in base-36.

Roadhouse answered 16/11, 2015 at 6:28 Comment(0)
P
3

I wrote some code to get this result.

Here's the code :

//==========================================

string Results = Encode(0.04036483168558814);

//==========================================


        private string Encode(double input)
        {

            var result = new Stack<char>();
            char[] clistarr = "0123456789abcdefghijklmnopqrstuvwxyz".ToCharArray();
            Int64 inputValInt = 0;
            string inputValP = "";
            double inputValN = 0;
            string ReturnsVal = "";
            if (input.ToString() != "")
            {
                try
                {
                    if (input.ToString().Contains("."))
                    {
                        inputValP = input.ToString().Substring(0, input.ToString().IndexOf("."));

                        inputValInt = Int64.Parse(inputValP);
                        if (inputValInt != 0)
                        {
                            while (inputValInt != 0)
                            {
                                result.Push(clistarr[inputValInt % 36]);
                                inputValInt /= 36;
                            }
                            char[] RevArr1 = result.ToArray();
                            Array.Reverse(RevArr1);
                            result = new Stack<char>();
                            for (int i = (RevArr1.Length - 1); i >= 0; i--)
                            {
                                result.Push(RevArr1[i]);
                            }
                            result.Push('.');
                        }
                        else
                        {
                            result.Push('0');
                            result.Push('.');
                        }
                        inputValN = input - inputValInt;
                        double inputVal = inputValN;

                        int CountLoop = 0;
                        while (CountLoop < 11)
                        {

                            double tempVal = (inputVal * 36);
                            int Start = tempVal.ToString("R").IndexOf(".");
                            if (Start > 0)
                            {
                                inputValP = tempVal.ToString("R").Substring(0, Start);

                                int TopVal = Int16.Parse(inputValP);
                                result.Push(clistarr[TopVal]);
                                inputVal = tempVal - TopVal;
                            }
                            CountLoop++;
                        }
                        char[] RevArr = result.ToArray();
                        Array.Reverse(RevArr);
                        ReturnsVal = new string(RevArr);
                    }
                    else
                    {
                        inputValInt = Convert.ToInt64(input);
                        while (inputValInt != 0)
                        {
                            result.Push(clistarr[inputValInt % 36]);
                            inputValInt /= 36;
                        }
                        char[] RevArr = result.ToArray();
                        ReturnsVal = new string(RevArr);
                    }

                }
                catch (Exception ee)
                {
                    return ("");
                }
            }
            else
            {
                return ("");
            }
            return (ReturnsVal);
        }
Phototelegraphy answered 14/1, 2016 at 4:35 Comment(0)
O
3

Here is a recursive function:

using System;

class Program {
   static string encode(int nIn, int nBase) {
      int n = nIn / nBase;
      char c = "0123456789abcdefghijklmnopqrstuvwxyz"[nIn % nBase];
      return n > 0 ? encode(n, nBase) + c : c.ToString();
   }

   static void Main() {
      var n = 1577858399;
      var s = encode(n, 36);
      Console.WriteLine(s == "q3ezbz");
   }
}
Old answered 3/11, 2020 at 2:29 Comment(1)
This is neat. Can you decode like that, too?Gerta
S
1

Thanks to user2032344 answer, I finally managed to get the same result as Javascript Math.random().toString(36) in C++/Qt

static QString JSMathRandomToString36(double input)
{
    static const auto clistarr = QByteArray("0123456789abcdefghijklmnopqrstuvwxyz");
    QString result;

    for(auto i = 0; i < 11 ; i++){
        auto tempVal = (input * 36);
        auto tempValStr = QString::number(tempVal, 'R');
        auto decIndex = tempValStr.indexOf(".");
        if (decIndex > 0) {
            auto topVal = tempValStr.mid(0, decIndex).toShort();
            result.append(clistarr[topVal]);
            input = tempVal - topVal;
        }
    }
    return (result);
}
Splenic answered 25/2, 2022 at 22:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.