Convert currency string to decimal?(将货币字符串转换为十进制?)
问题描述
对一个string进行排序,该string在一组数据中以数字形式显示类似$1,995.94的货币数据.
Sort a string that is displaying currency data like this $1,995.94 numerically in a set of data.
我目前正在使用以下代码示例将 string 值转换为 decimal 以便我可以对其进行正确排序.
I'm currently using the below code sample to convert the string value to decimal so that I can sort it properly.
if (sortBy == "checkAmount")
{
StringBuilder sb = new StringBuilder();
foreach (var c in Convert.ToString(p.GetType().GetProperty(sortBy).GetValue(p, null)))
{
if (!char.IsDigit(c) && c != '.') { continue; }
sb.Append(c);
}
return Convert.ToDecimal(sb.ToString());
}
else
{
return p.GetType().GetProperty(sortBy).GetValue(p, null);
}
问题
有什么更好的方法来做到这一点?它有效,这很酷,但它不是很优雅.
Problem
What's a better way of doing this? It works, and that's cool, but it's not very elegant.
Servy 提供的答案 按预期工作,我将该实现用于虽然,但我和一位同事找到了一个更好的方法,所以我在这里记录它.顺便说一句,我最终还是使用了这个解决方案.
The answer provided by Servy works as expected, and I used that implementation for a while, but a colleague and I found an even better way so I'm documenting it here. BTW, I ended up using this solution in the end.
decimal.Parse(input, NumberStyles.AllowCurrencySymbol | NumberStyles.Number);
推荐答案
这是一个与您提供的代码最相似的方法
Here is a method that most closely resembles the code you've provided
public static decimal Parse(string input)
{
return decimal.Parse(Regex.Replace(input, @"[^d.]", ""));
}
这是一个支持负数的选项,如果找到第二个句点值,它将停止,从而减少它返回的无效 decimal 值的字符串数量.它还有一些在 OP 中看不到的其他修改,以处理当前代码没有的其他情况.
Here is an option that will support negative numbers, and will stop if it finds a second period value, thus reducing the number of strings it returns that are not valid decimal values. It also has a few other modifications not seen in the OP to handle additional cases your current code doesn't.
public static decimal Parse(string input)
{
return decimal.Parse(Regex.Match(input, @"-?d{1,3}(,d{3})*(.d+)?").Value);
}
这篇关于将货币字符串转换为十进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将货币字符串转换为十进制?
基础教程推荐
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 将数据集转换为列表 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 如果条件可以为空 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
