Dev Null Fin
Dev Null Fin

Reputation: 183

Find Currency Symbol in Currency Data C#

I want to find which Currency Symbol exists in Currency Format data.

For example, Input String = $56.23

public class FormatConverter 
{
    private CultureInfo _cultureInfo;

    public void UpdateCultureInfo()
    {
        Thread.CurrentThread.CurrentCulture.ClearCachedData();
        var thread = new Thread(
            s => _cultureInfo = Thread.CurrentThread.CurrentCulture);

        thread.Start();
        thread.Join();
    }

    Bool TryParseCurrencySymbolAndValue(string input, out string CurrencySymbol,
                                        out double value)
    {
        if(_cultureInfo == null)
            UpdateCultureInfo();
        try{

        // Convert Currency data into double
        value = Double.Parse(input, NumberStyles.Number | NumberStyles.AllowCurrencySymbol);
        // How to extract Currency Symbol?
            CurrencySymbol = "$";
            return true;
        }
        catch(Exception ex){ /* Exception Handling */}
        return false;
    }
}

I want to extract "$" symbol from a string and 56.23 separately and then I want to apply CultureInfo to 56.23 into French Format. The output should be $56,23.

In some cases, input might be "Euro sign" or some other currency symbol in the beginning or in the end of input string.

I know how to convert into CurrentCulture for Numeric part. I don't know how to extract currency Symbol from a string.

Upvotes: 3

Views: 3236

Answers (3)

Nathan
Nathan

Reputation: 1090

It sounds like you already know how to parse the string into a number type (correct me if I'm wrong). You're using double in your example, I would suggest decimal but that's your choice.

To get the currency symbol you can use a simple regular expression

Regex ex = new Regex(@"\p{Sc}");
CurrencySymbol = ex.Match(input).Value;

I hope that helps.

Upvotes: 6

MethodMan
MethodMan

Reputation: 18863

Look at this link as well to give you and idea as to the many different ways you can find and or use IndexOf [IndexOf String Examples][1]

the question is will the format always have the $ as the first char..? if the answer is yes regardless of USC or Foreign Currency use the String.IndexOf Method

String.IndexOf("$")

here is a coded example that you may look at

using System;

class Program
{
    static void Main()
    {
    // A.
    // The input string.
    const string s = "Tom Cruise is an Idiot he should pay $54.95.";

    // B.
    // Test with IndexOf.
    if (s.IndexOf("$") != -1)
    {
        Console.Write("string contains '$'");
    }
    Console.ReadLine();
    }
}

Output

string contains '$'

Upvotes: 1

CodeMad
CodeMad

Reputation: 948

Can you please try with?

float curSymbol;
bool isValid = float.TryParse(curValue, 
    NumberStyles.Currency,
    CultureInfo.GetCultureInfo("en-US"), out curSymbol);

Get the curSymbol. :) Be sure to pass currency values with symbol:)

Upvotes: -2

Related Questions