Dragan
Dragan

Reputation: 47

string to double parsing error

i have the following code:

    static void Main(string[] args)
    {
        Thread.CurrentThread.CurrentCulture = new CultureInfo("mk-MK");
        string s2 = "4.434,00";

        double d;

        if (Double.TryParse(s2, NumberStyles.Number, CultureInfo.CurrentCulture, out d))
        {
            //String.Format("{0:0.0,00}", d);
            Console.WriteLine(d + " Type of: " + d.GetType());
        }
        else
        {
            Console.WriteLine("ne go parsirashe");
        }

        String.Format("{0:0.0,00}", d);
        Console.WriteLine(d);


        //Console.WriteLine(String.Format("{0:0,0.00}", d));


        //Console.WriteLine(s2.GetType().ToString());
        //Console.ReadLine();

        //String.Format("{0:0.0,00}"
        Console.ReadLine();

The output is: 4434 Type of: System.Double 4434

Why isn't the value of d in the format of : 4.434,00 ? Can you please help me with this? I've sent couple of hours trying to figure this out before trying to reach out to you guys. Thanks!!!

Upvotes: 0

Views: 1148

Answers (3)

porges
porges

Reputation: 30580

You have the . and , around the wrong way, if I'm understanding what you're trying to do.

If you read the Custom Numeric Format Strings page on MSDN, you can see that you need to use , for the thousands separator, and . for the decimal separator, and (the important part) the target culture is irrelevant here. The format is always the same, regardless of the current culture.

So what you want to use is:

Console.WriteLine("{0:0,0.00}", d);

Then the output is:

4434 Type of: System.Double
4.434,00

Upvotes: 1

Oded
Oded

Reputation: 499002

You are discarding your formatted string - you are not assigning it to a string and simply outputting the double to the console (which would call ToString() on it).

Try this:

string forDisplay = string.Format("{0:0.0,00}", d);
Console.WriteLine(forDisplay);

Or, even shorter:

Console.WriteLine(string.Format("{0:0.0,00}", d));

Update:

In order to format the string according to your culture, you will need to use the Format overload that takes an IFormatProvider (i.e. a culture) and ensure that the format string uses the right characters for the different parts (, for standard thousands separator and . for standard decimal separator - see here for the meanings of each such character in a format string):

var res = String.Format(CultureInfo.CurrentCulture, "{0:0,0.00}", d);
Console.WriteLine(forDisplay);

Result:

4.434,00

Upvotes: 1

Cameron
Cameron

Reputation: 98746

You meant to do:

string formatted = String.Format("{0:0.0,00}", d);
Console.WriteLine(formatted);

string.Format returns a string -- it cannot affect the formatting of a double, since doubles have no formatting at all. Doubles only store the raw numeric value (as bits, internally).

Upvotes: 1

Related Questions