转换货币字符串转换为十进制? [英] Convert currency string to decimal?

查看:145
本文介绍了转换货币字符串转换为十进制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标

排序字符串,其中显示货币数据类似这样的 $ 1,995.94 数值在一组数据。

code

我目前使用下面的code样品的<​​code>字符串转换值十进制使我能够正确排序。

 如果(sortBy ==checkAmount)
{
    StringBuilder的SB =新的StringBuilder();
    的foreach(VAR c在Convert.ToString(p.GetType()的getProperty(sortBy).GetValue(P,NULL)))
    {
        如果(char.IsDigit(C)及!&安培;!C =''){继续; }
        sb.Append(C);
    }
    返回Convert.ToDecimal(sb.ToString());
}
其他
{
    返回p.GetType()的getProperty(sortBy).GetValue(P,空)。
}
 

问题

什么是这样做的更好的办法?它的工作原理,这是很酷,但它不是很优雅。

最终解决方案

由Servy 提供的答案按预期工作,然后我用实施了一段时间,但我和一个同事发现了一个更好的办法,所以我在这里记录了。 顺便说一句,我结束了使用该解决方案到底。

  decimal.Parse(输入,NumberStyles.AllowCurrencySymbol | NumberStyles.Number);
 

解决方案

下面是最近似于您所提供的code的方法

 公共静态十进制解析(字符串输入)
{
    返回decimal.Parse(Regex.Replace(输入,@[^ \ D。],));
}
 

下面是支持负数的选项,如果发现第二个周期值,从而减少它返回无效的十进制串的数量将停止值。它也有在OP没有看到以处理更多的情况下,其他一些修改,你现在的code没有。

 公共静态十进制解析(字符串输入)
{
    返回decimal.Parse(Regex.Match(输入@ -  \ D {1,3}(,\ D {3})*(\ \ D +)?。?)值。);
}
 

Objective

Sort a string that is displaying currency data like this $1,995.94 numerically in a set of data.

Code

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.

Final Solution

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.]", ""));
}

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆