Convert currency string to decimal?

后端 未结 6 932
北恋
北恋 2020-12-05 13:00

Objective

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

Code

I\'m cu

6条回答
  •  爱一瞬间的悲伤
    2020-12-05 13:24

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

提交回复
热议问题