简体   繁体   English

需要建议从字符串中解析十进制值

[英]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 QUANTITY->节省空间> 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 您可以将Regex与累加器一起使用,自定义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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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