首页 > 解决方案 > C# 字符串到所有样式或文化的十进制

问题描述

嗨,我想查找是否有更好的方法将字符串解析为涵盖各种格式的十进制

  1. 1.30 美元
  2. 1.50 英镑
  3. 2,50 欧元
  4. 2,50 欧元</li>
  5. 2.500,00 欧元</li>

我看到很多使用文化来转换.& 的例子,。但就我而言,我没有任何东西可以识别文化。

我从客户端获得的这个显示字段,我需要提取值。

我尝试了以下操作(不适用于所有场景),但想知道我们是否有最好的方法来处理这个问题。

Decimal.Parse(value,NumberStyles.Currency |
                    NumberStyles.Number|NumberStyles.AllowThousands |
                    NumberStyles.AllowTrailingSign | NumberStyles.AllowCurrencySymbol)

我还尝试使用 Regex 删除货币符号,但无法在一个逻辑中同时转换 1.8 或 1,8。

标签: c#.netc#-4.0decimal

解决方案


好吧,假设您始终获得有效的货币格式,并且只是文化发生变化,您可以通过检查数字中最后出现的字符来猜测哪个字符用作小数点,哪个字符用作千位分隔符。然后删除所有的一千个分隔符并解析它,就像它的文化是不变的一样。

代码如下所示:

// Replace with your input
var numberString = "2.500,00  €";

// Regex to extract the number part from the string (supports thousands and decimal separators)
// Simple replace of all non numeric and non ',' '.' characters with nothing might suffice as well
// Depends on the input you receive
var regex = new Regex"^[^\\d-]*(-?(?:\\d|(?<=\\d)\\.(?=\\d{3}))+(?:,\\d+)?|-?(?:\\d|(?<=\\d),(?=\\d{3}))+(?:\\.\\d+)?)[^\\d]*$");

char decimalChar;
char thousandsChar;

// Get the numeric part from the string
var numberPart = regex.Match(numberString).Groups[1].Value;

// Try to guess which character is used for decimals and which is used for thousands
if (numberPart.LastIndexOf(',') > numberPart.LastIndexOf('.'))
{
    decimalChar = ',';
    thousandsChar = '.';
}
else
{
    decimalChar = '.';
    thousandsChar = ',';
}

// Remove thousands separators as they are not needed for parsing
numberPart = numberPart.Replace(thousandsChar.ToString(), string.Empty);

// Replace decimal separator with the one from InvariantCulture
// This makes sure the decimal parses successfully using InvariantCulture
numberPart = numberPart.Replace(decimalChar.ToString(),
    CultureInfo.InvariantCulture.NumberFormat.CurrencyDecimalSeparator);

// Voilá
var result = decimal.Parse(numberPart, NumberStyles.AllowDecimalPoint | NumberStyles.Number, CultureInfo.InvariantCulture);

对于简单的十进制解析来说,它看起来确实有点复杂,但我认为应该为你得到的所有输入数字或至少大部分输入数字做这项工作。

如果您在某种循环中执行此操作,您可能希望使用已编译的正则表达式。


推荐阅读