Introduction
The two functions convert/parse number strings with prefix multipliers (Milli, Kilo, Mega, Giga, etc.).
ParsePrefix
"124.67uH" >> 1.2467e-4
"124670uH" >> 1.2467e-7
"124.67mW" >> 1.2467e-1
"124.67MW" >> 1.2467e8
"100pF" >> 1e-10
AddPrefix
0.1123123 >> "112.3123m"
112312.3 >> "112.3123K"
1000 >> "1K"
1000000000000, "B" >> "1TB"
Here is the code:
public static double ParsePrefix(string value)
{
string[] superSuffix = new string[] { "K", "M", "G", "T", "P", "A", };
string[] subSuffix = new string[] { "m", "u", "n", "p", "f", "a" };
char sufChar = '\0';
foreach (char c in value)
{
foreach (string s in subSuffix)
if (c.ToString() == s)
{
sufChar = c;
string num = value.Substring(0, value.IndexOf(sufChar));
return Convert.ToDouble(num) / Math.Pow(1000,
subSuffix.ToList().IndexOf(sufChar.ToString()) + 1);
}
foreach (string s in superSuffix)
if (c.ToString().ToLower() == s.ToLower())
{
sufChar = s[0];
string num = value.Substring(0, value.IndexOf(c));
double mult = Math.Pow(1000, superSuffix.ToList().IndexOf
(sufChar.ToString()) + 1);
return Convert.ToDouble(num) * mult;
}
}
return Convert.ToDouble(value);
}
public static string AddPrefix(double value, string unit = "")
{
string[] superSuffix = new string[] { "K", "M", "G", "T", "P", "A", };
string[] subSuffix = new string[] { "m", "u", "n", "p", "f", "a" };
double v = value;
int exp = 0;
while (v - Math.Floor(v) > 0)
{
if (exp >= 18)
break;
exp += 3;
v *= 1000;
v = Math.Round(v, 12);
}
while (Math.Floor(v).ToString().Length > 3)
{
if (exp <= -18)
break;
exp -= 3;
v /= 1000;
v = Math.Round(v, 12);
}
if (exp > 0)
return v.ToString() + subSuffix[exp / 3 - 1] + unit;
else if (exp < 0)
return v.ToString() + superSuffix[-exp / 3 - 1] + unit;
return v.ToString() + unit;
}