Sum*_*ngh 0 c# regex formatting currency
我需要将输入货币(不带小数位)的格式设置为标准方式(如$XXX,XXX,XXX,XXX)。用户可以输入以下任何内容:
$123 $123,123 $1,123,123 123,123 12,123,123 12312312 123 $12123123我已经写了一篇文章Regex,我可以通过该文章找到所需的模式-> ^\$?[0-9]{1,3}(?:(,[0-9]{3})*|([0-9]{3})*)?$但我不明白如何编写替代代码来格式化上述示例以进行$XXX,XXX,XXX,XXX...格式化(因为没有固定的组可以选择)。
我建议使用解析和格式化来代替正则表达式:
Func<string, string> beautify = (value) => decimal
.Parse(value, // parse initial value as
NumberStyles.Currency, // currency
CultureInfo.GetCultureInfo("en-US")) // of the US
.ToString("c0", // format as currency (no cents)
CultureInfo.GetCultureInfo("en-US")); // of the US
Run Code Online (Sandbox Code Playgroud)
演示:
string[] tests = new string[] {
"$123",
"$123,123",
"$1,123,123",
"123,123",
"12,123,123",
"12312312",
"123",
"$12123123",
};
string demo = string.Join(Environment.NewLine, tests
.Select(test => $"{test,-15} -> {beautify(test)}"));
Console.Write(demo);
Run Code Online (Sandbox Code Playgroud)
结果:
$123 -> $123
$123,123 -> $123,123
$1,123,123 -> $1,123,123
123,123 -> $123,123
12,123,123 -> $12,123,123
12312312 -> $12,312,312
123 -> $123
$12123123 -> $12,123,123
Run Code Online (Sandbox Code Playgroud)