Click here to Skip to main content
15,883,705 members
Articles / Programming Languages / C#
Tip/Trick

Convert and Parse Prefix Multipliers - C#

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
1 Jun 2018CPOL 10.9K   1   1
The two functions convert/parse number strings with prefix multipliers (Milli, Kilo, Mega, Giga, etc). The code includes try/catch blocks for tolerating writing styles.

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:

C#
/// <summary>
/// Parses a prefix number to double. Unit is ignored.
/// Prefixes greater than 1 ([K]ilo, [G]ega etc) etc are case insensitive.
/// (However, m is milli, M is Mega)
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
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);
}

/// <summary>
/// Selects a suitable prefix for the value to keep 1-3 significant figures
/// on the left of the decimal point.
/// </summary>
/// <param name="value"></param>
/// <param name="unit">Optional unit to be put after the prefix</param>
/// <returns></returns>
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;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer techCREATIONS
Pakistan Pakistan
Developer, Programmer, Beta Tester; technically, i'm none of these. I'm a mechanical engineer, programming is my passion, my hobby and my amateur non profit profession. I program when ii need and innovate whenever, wherever i want.

Learned:
C#

Mixed:
C#+Applied Mathematicss-Robotics+C++

Developed:
C# OMR Reader
Monopoly (Urdu language)
HybridAutomation Framework
SMS Bomber (Windows Mobile 6 Professional)
Hard disk watch tower
Farmville Super Clicker
Games Profile selector
Windows mobile salat reminder
Windows mobile SMS Pole Host
and alot of other small apps

Comments and Discussions

 
QuestionMinor suggestion Pin
varnk9-Aug-19 4:01
varnk9-Aug-19 4:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.