SymboCoder
SymboCoder

Reputation: 147

How to remove non-numeric from a string but retain decimal in C#

I am using Selenium(C#) on NUnit Framework and is getting a string from UI as $4850.19. I want to compare above string with the value from backend (DB) to assert they are equal. I am using a below method to parse my dollar amount from front-end, but the issue is that is also stripping the decimal point; and obviously the comparison with backend is failing.

Method used:

 public static string RemoveNonNumeric(string s)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.Length; i++)
            if (Char.IsNumber(s[i]))
                sb.Append(s[i]);
        return sb.ToString();
    }

How to strip out any '$' or ',' but keep '.' in the value?

Upvotes: 2

Views: 5533

Answers (4)

Rufus L
Rufus L

Reputation: 37020

Another way to do it if you don't want to go the decimal.Parse route is to simply return only numeric and '.' characters from the string:

public static string RemoveNonNumeric2(string s)
{
    return string.Concat(s?.Where(c => char.IsNumber(c) || c == '.') ?? "");
}

Upvotes: 4

SymboCoder
SymboCoder

Reputation: 147

Thanks for all inputs above, I kind of figured out an easy way to handle this for now (as shown below) -

public static string RemoveNonNumeric(string s)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.Length; i++)
            if (Char.IsNumber(s[i]) || s[i] == '.')
                sb.Append(s[i]);
        return sb.ToString();
    }

I would like to try other ways of handling this as well soon.

Upvotes: 0

Rufus L
Rufus L

Reputation: 37020

You can also use the decimal.Parse method to parse a string formatted as currency into a decimal type:

string input = "$4,850.19";
decimal result = decimal.Parse(input, NumberStyles.Currency);

Console.WriteLine($"{input} => {result}");

Output:

enter image description here

Upvotes: 4

Vadim Alekseevsky
Vadim Alekseevsky

Reputation: 487

With Reg ex it's trivial

Regex.Replace(s, "[^0-9.]", "")

Upvotes: 9

Related Questions