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