1

Scenario:

Step 1: Get decimal value
Step 2: Use culture info to display proper currency
Step 3: Results:

"$100.0000"
"£24.0340"
"11,0400 €"

Step 4: Use trimend for £ and $ where symbols are before numbers:

    input = input.TrimEnd("0".ToCharArray());
    input = input.TrimEnd(".".ToCharArray());

Output:
"$100"
"£24.034"
"11,0400 €"

If zeros or dot is in the end it is simple, but then it breaks when other char is in the end in case of € culture.

What would be the best way to remove trailing zeros from a different strings without doing complex job on string manipulation? Is this even proper way I am doing it?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
sensei
  • 7,044
  • 10
  • 57
  • 125
  • What happened to the original decimal value? – Steve Jul 19 '14 at 16:29
  • First remove currency symbols - on both ends, then trim whitespace on both ends, then trim the decimals at the right side. You cannot do that all at once, only step by step. – Roland Pihlakas Jul 19 '14 at 16:30
  • Or you could strip any non-numerical values as the first step, or even use regular expressions to extract the numerical value, excluding trailing zeros. – Roland Pihlakas Jul 19 '14 at 16:42
  • Simply removing all trailing zeroes doesn't seem to be correct. For example, "$100.5000" should be changed to "$100.50", not "$100.5". – Michael Liu Jul 19 '14 at 17:15
  • @MichaelLiu "$100.5" is extremely uncommon, but by what logic can you say it is incorrect? –  Jul 19 '14 at 17:22
  • That said, somewhat similar to what Michael Liu commented: your step 2 "Use culture info to display proper currency" shouldn't be giving you the results you are getting. Converting a decimal value to a string based on the culture's currency format won't give you four decimals for euros, for British pounds or US dollars: they all default to two decimals, so the only way to get four decimals is if you're *not* using the culture info to make that determination. What is it you're doing in step 2? –  Jul 19 '14 at 17:30
  • I am forcing amount of decimal digits with `nfi.CurrencyDecimalDigits = 4;` but thats another story. – sensei Jul 19 '14 at 17:42
  • @AmelSalibasic Not exactly another story. The whole point of your question is about the number of decimals -- you want to reduce it. And your previous code, that you didn't show, increased the number of decimals. So that seems like it made your problem worse. I would approach it differently, and not set `nfi.CurrencyDecimalDigits`, but instead check the correct number of decimals (by whatever logic you want) beforehand, and then use the format string for that number of decimals (for example, if you've determined that 24.034m should show three decimals, use `"C3"`). –  Jul 20 '14 at 09:19

2 Answers2

0

Use CurrencySymbol to get the current currency :

Char currentCurrency = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol.ToCharArray()[0];

// Get your Double number,
Double result = null;

try {
    Regex regexObj = new Regex(@"[^\d]");
    result = Convert.ToDouble(regexObj.Replace(input, ""));
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}

Switch(currentCurrency){
  // Append or prepend your currency symbol to your input
}

If you need to change thread currency use this code to get current thread currency symbol :

System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencySymbol

Sources : Link 1, Link 2

Community
  • 1
  • 1
0

Problem is you cannot use NumberFormatInfo class to get proper culture object and at the same time trail zeros... So you have to do some manipulation on string if you want to achieve what I needed.

Output I wanted:

"$10.2"
"£50.465"
"23,54 €"

As per standards for writting currencies natively.

I resolved with complex string manipulation (aka some work on strings)...

public static string LocalizeJackpots(this HtmlHelper html, decimal amount, byte currencyType)
{
    var httpContext = new HttpContextWrapper(HttpContext.Current);

    string countryCulture = httpContext.Request.Cookies["countryCulture"].Value;

    var culture = GetCultureByCurrencyType(currencyType, countryCulture);

    return ManipulateCurrencyString(amount.ToString("c", culture));
}

And then:

/// <summary>
        /// This is used to properly trail leading zeros with usage of NumberFormatInfo culture class later in string
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
private static string ManipulateCurrencyString(string input)
        {
            char lastCharacter = input.Substring(input.Length - 1, 1)[0];

            if (Char.IsNumber(lastCharacter))
            {
            // for currencies with symbol in front
            input = input.TrimEnd("0".ToCharArray()).TrimEnd(".".ToCharArray());
            }
            else
            {
            // for currencies with symbol in the end
            string symbol = input.Substring(input.Length - 1, 1);
            string number = input.Substring(0, input.Length - 2).TrimEnd("0".ToCharArray()).TrimEnd(".".ToCharArray()).TrimEnd(",".ToCharArray());

            input = number + " " + symbol;
            }

            return input;
        }
sensei
  • 7,044
  • 10
  • 57
  • 125