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);
}
这篇关于将货币字符串转换为十进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将货币字符串转换为十进制?


基础教程推荐
- c# Math.Sqrt 实现 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01