C# 字符串在所有样式或文化上转为十进制

Raj*_*Gan 2 .net c# decimal c#-4.0

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

\n\n
    \n
  1. 1.30 美元
  2. \n
  3. \xc2\xa31.50
  4. \n
  5. \xe2\x82\xac2,50
  6. \n
  7. 2,50 \xc2\xa0\xe2\x82\xac
  8. \n
  9. 2.500,00 \xc2\xa0\xe2\x82\xac
  10. \n
\n\n

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

\n\n

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

\n\n

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

\n\n
Decimal.Parse(value,NumberStyles.Currency |\n                    NumberStyles.Number|NumberStyles.AllowThousands |\n                    NumberStyles.AllowTrailingSign | NumberStyles.AllowCurrencySymbol)\n
Run Code Online (Sandbox Code Playgroud)\n\n

我还尝试使用正则表达式删除货币符号,但无法在一种逻辑中同时转换 1.8 或 1,8。

\n

Ima*_*tas 5

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

\n\n

代码如下所示:

\n\n
// Replace with your input\nvar numberString = "2.500,00  \xe2\x82\xac";\n\n// Regex to extract the number part from the string (supports thousands and decimal separators)\n// Simple replace of all non numeric and non \',\' \'.\' characters with nothing might suffice as well\n// Depends on the input you receive\nvar regex = new Regex"^[^\\\\d-]*(-?(?:\\\\d|(?<=\\\\d)\\\\.(?=\\\\d{3}))+(?:,\\\\d+)?|-?(?:\\\\d|(?<=\\\\d),(?=\\\\d{3}))+(?:\\\\.\\\\d+)?)[^\\\\d]*$");\n\nchar decimalChar;\nchar thousandsChar;\n\n// Get the numeric part from the string\nvar numberPart = regex.Match(numberString).Groups[1].Value;\n\n// Try to guess which character is used for decimals and which is used for thousands\nif (numberPart.LastIndexOf(\',\') > numberPart.LastIndexOf(\'.\'))\n{\n    decimalChar = \',\';\n    thousandsChar = \'.\';\n}\nelse\n{\n    decimalChar = \'.\';\n    thousandsChar = \',\';\n}\n\n// Remove thousands separators as they are not needed for parsing\nnumberPart = numberPart.Replace(thousandsChar.ToString(), string.Empty);\n\n// Replace decimal separator with the one from InvariantCulture\n// This makes sure the decimal parses successfully using InvariantCulture\nnumberPart = numberPart.Replace(decimalChar.ToString(),\n    CultureInfo.InvariantCulture.NumberFormat.CurrencyDecimalSeparator);\n\n// Voil\xc3\xa1\nvar result = decimal.Parse(numberPart, NumberStyles.AllowDecimalPoint | NumberStyles.Number, CultureInfo.InvariantCulture);\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n

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

\n