Ron
Ron

Reputation: 287

C# string with particular character at end to integer

I could probably do this in a series of steps by looking at the last character of the string and based on what it is send it to a particular function to have the conversion made. But I am just wondering if there is any easier way to do the following.

For example I have a string that might say something like 23.44M or 5.23B, the M and B obviously stand for "Million" or "Billion", I want to convert that string into the number it is representing but just not sure of the most efficient way to do this. Looking for some ideas. Thanks

Upvotes: 4

Views: 257

Answers (6)

Myles McDonnell
Myles McDonnell

Reputation: 13335

Use a dictionary to map chars to multipliers instead of a switch statement and use upper case only:

public static decimal GetValue(string number)
{
    return decimal.Parse(number.Remove(number.Length - 1, 1)) *  _multipliers[number.Last().ToUpper()];
}

Upvotes: 0

Muad'Dib
Muad'Dib

Reputation: 29246

your best bet is probably to use a regex (MSDN docs here) you could group on (this is NOT regex syntax) [numbers][char] then you have 2 groups, the first would be your number, the second would be your "factor" character

then, convert the first with double.TryParse(), and run your second through a switch or a set of if statements to multiply as needed to get your end result.

Upvotes: 0

Eugen Rieck
Eugen Rieck

Reputation: 65304

As a nerdy alternative to the answer by @Smelch you could populate a String constant POSTFIXES, such as "xHKxxMxxBxxTxxQ" and multiply your base by Math.Pow(10,POSTFIXES.LastIndexOf(...)+1)

Upvotes: 0

Strillo
Strillo

Reputation: 2982

/// <summary>
/// Gets the value.
/// </summary>
/// <param name="number">The number.</param>
/// <returns></returns>
public static decimal GetValue(string number)
{
    char unit = number.Last();
    string num = number.Remove(number.Length - 1, 1);

    decimal multiplier;
    switch (unit)
    {
        case 'M':
        case 'm':
            multiplier = 1000000; break;

        default:
            multiplier = 1; break;
    }

    return decimal.Parse(num) * multiplier;
}

Upvotes: 0

Sogger
Sogger

Reputation: 16142

Something along these lines work for you?

double num = Double.parse(inputStr.Remove(inputStr.Count-1));
char lastChar = inputStr.Last();
switch(lastChar)
{
   case 'M':
      num *= 1000000;
      break;
   case 'B':
      num *= 1000000000;
      break;
}

If the format of your input can vary, you would have to add additional logic, including protecting against an illegal Parse().

Upvotes: 1

smelch
smelch

Reputation: 2543

I would build a Dictionary, and populate it with key value pairs such as (B, 1,000,000,000) and (M, 1,000,000). Take the character off the end, look up the value for that character, and multiply.

Upvotes: 6

Related Questions