Vinshi
Vinshi

Reputation: 313

Getting a negative decimal from a currency string

I have a string with currency symbol. I need to extract just the decimal along with the negative sign.

Here are some examples of the string and the desired decimal value:

-$ 100 : -100 
C$ 400.68 : 400.68
-$ 578.89: -578.89

This is the code that I am using currently.

        var match = Regex.Match(valueToParse, @"-?[0-9]*\.?[0-9]+");
        if (match.Success)
        {
            decimal.TryParse(match.Value, out result);
        }

It works for extracting decimal numbers but does not work for the 1st and 3rd example. Any suggestion is appreciated.

Upvotes: 2

Views: 310

Answers (2)

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

You can replace everything except -, digits and . using this regex with empty string,

[^-\d\n.]+

which will leave you only with your desired number with negative sign.

Demo

C# Demo

Regex regex = new Regex(@"[^-\d\n.]+");
string input = "-$ 100";
string result = regex.Replace(input, "");
Console.WriteLine(input + " --> " + result);
input = "C$ 400.68";
result = regex.Replace(input, "");
Console.WriteLine(input + " --> " + result);
input = "-$ 578.89";
result = regex.Replace(input, "");
Console.WriteLine(input + " --> " + result);

Prints,

-$ 100 --> -100
C$ 400.68 --> 400.68
-$ 578.89 --> -578.89

Upvotes: 4

Vqf5mG96cSTT
Vqf5mG96cSTT

Reputation: 2891

You can use capture groups for this. One for the sign and the other for the amount. Then you can concatenate both and try to parse it as a decimal.

The regex I'm using below has a couple of assumptions. But it should fit the use cases you brought forward.

var valueToParse = "-$ 578.89";
var match = Regex.Match(valueToParse, @"^(?<sign>-?).*? (?<amount>\d+(\.\d+)?)$");
if (match.Success)
{
    decimal.TryParse($"{match.Groups["sign"]}{match.Groups["amount"]}", out var result);

    Console.WriteLine(result);
}

Upvotes: 1

Related Questions