C # string with a specific character at the end to the whole

Perhaps I could do this in a few steps by looking at the last character of the string and based on what it sends to a specific function for conversion. But I'm just wondering if there is an easier way to do the following.

For example, I have a string that can say something like 23.44M or 5.23B, M and B explicitly mean "Million" or "Billion", I want to convert this string to the number that it represents, but just not sure the most effective way of doing this. Looking for some ideas. Thanks

+4
source share
6 answers
/// <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; } 
0
source

I would build a dictionary and populate it with pairs of key values, such as (B, 1,000,000,000) and (M, 1,000,000). Take the symbol from the end, find the value for this symbol and multiply it.

+6
source

Is something in this direction working 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 may differ, you will have to add additional logic, including protection against illegal Parse ().

+1
source

it’s best to use a regular expression ( MSDN docs here ), you can group (this is NOT the regex syntax) [numbers] [char] then you have 2 groups, the first will be your number, the second will be your "factor"

then convert the first with double.TryParse() and run your second through a switch or a set of if to multiply them to get the final result.

0
source

As a more reliable alternative to @Smelch's answer, you can fill in a String POSTFIXES constant, such as "xHKxxMxxBxxTxxQ", and multiply your base by Math.Pow (10, POSTFIXES.LastIndexOf (...) + 1)

0
source

Use a dictionary to match characters in multipliers instead of a switch statement and use only uppercase:

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

Source: https://habr.com/ru/post/1387224/


All Articles