2

I am trying here to parse a number using the Gabon currency formating.

The format uses "." for group separations and no decimals.

Here is an example :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Threading;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            CultureInfo ci = new CultureInfo("fr-FR");

            ci.NumberFormat.CurrencyGroupSeparator = ".";
            ci.NumberFormat.CurrencyDecimalDigits = 0;
            ci.NumberFormat.CurrencySymbol = "CFA";

            Thread.CurrentThread.CurrentCulture = ci;
            Thread.CurrentThread.CurrentUICulture = ci;

            double.Parse("300.000", ci).ToString("C"); 
                    // gives me a FormatException
        }
    }
}

Is there something I am missing ?

Mare Infinitus
  • 8,024
  • 8
  • 64
  • 113
Erick
  • 5,969
  • 10
  • 42
  • 61
  • 3
    Your comment is incomplete. It's not clear what you're expecting vs what you got. I will say that you should be using `decimal` instead of `double` for currency values though... – Jon Skeet Jul 23 '12 at 20:20
  • I was trying to parse it using the format the Gabonese use. Altough I am not able to parse it I always get an exception on the `double.Parse` part. – Erick Jul 23 '12 at 20:49
  • I added Robert's line and I was able to parse in a console application. It's not working using MVC's ModelBinder but I guess it's a start. – Erick Jul 23 '12 at 20:53

2 Answers2

3

In your case, you have to help .NET a little - when simply using Parse like that, it assumes you want to get a number. French culture uses , as a decimal separator and that is the reason your code throws an exception.

Try this, instead:

double.Parse("300.000", NumberStyles.Currency, ci).ToString("C");

Now, the string will get correctly parsed as currency, respecting the currency rules you have specified in the ci culture.

And - as others have said, you should really use decimal when dealing with currency. Double is simply not precise enough.

Community
  • 1
  • 1
Nikola Anusev
  • 6,940
  • 1
  • 30
  • 46
1

add this: ci.NumberFormat.NumberGroupSeparator = ".";

Robert Levy
  • 28,747
  • 6
  • 62
  • 94