简体   繁体   中英

Need advice parsing decimal value from the string

I need to parse quantity as decimal and currency code as string.

Input string

302 600.00 RUB
10 000.00 USD

The pattern is

  1. QUANTITY->SPACE->CURRENCYCODE
  2. TWO DECIMAL DIGITS
  3. Space as thousand separator, dot as decimal separator

This isn't tested but you could do something like this.

string text = "302 600.00 RUB";
decimal amount;
string type;

var lastspace = text.lastIndexOf(" ");    
decimal.TryParse(text.substring(0, lastspace - 1), out amount);
type = text.substring(lastspace + 1);

Hope this helps.

using System.Text.RegularExpressions;

[...]

string sInput = "302 10 600.00 RUB";
// string sInput = "302 600.00 RUB";
// string sInput = "10 000.00 USD";

var rgmResult = Regex.Match(sInput, @"^(?<qty>\d+) (?<price>\d{1,3}( \d{3})*\.\d{2}) (?<cur>[A-Z]{3})$");
string sQuantity = rgmResult.Groups["qty"].Value;
string sPrice = rgmResult.Groups["price"].Value;
string sCurrency = rgmResult.Groups["cur"].Value;

You can use Regex with accumulators, custom NumberFormat

string pattern = @"(?<decimal>[0-9]{0,3}(\s[0-9]{3})*(.[0-9]+){0,1})\s" +
                 @"(?<currency>[a-zA-Z]+){1}";

string input = "302 600.00 RUB\r\n10 000.00 USD"; 

// Get text that matches regular expression pattern.
MatchCollection matches = Regex.Matches(input, pattern, RegexOptions.IgnoreCase);

NumberFormatInfo format = new NumberFormatInfo();
format.NumberGroupSeparator = " ";
format.NumberDecimalSeparator = ".";
format.NumberDecimalDigits = 2;

Dictionary<string, decimal> dictionary = new Dictionary<string, decimal>();
foreach (Match match in matches)
{
    dictionary.Add(match.Groups["currency"].Value, Decimal.Parse(match.Groups["decimal"].Value, format));      
}
if (dictionary.Count > 0)
{
    foreach (KeyValuePair<string, decimal> item in dictionary)
    {
        Console.WriteLine("Currency : {0} Amount: {1}", item.Key, item.Value);
    }
}

Output is:

Currency : RUB Amount: 302600,00
Currency : USD Amount: 10000,00

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM