将货币字符串转换为十进制?

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);
}

这篇关于将货币字符串转换为十进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)