Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# decimal separator?

I have a method which returns numbers like this:

public decimal GetNumber()
{
    return 250.00m;
}

Now when this value is printed to the console for example, it has a comma (250,00) instead of a point (250.00). I always want a point here, what am I doing wrong?

like image 925
grady Avatar asked Oct 06 '10 07:10

grady


Video Answer


3 Answers

decimal itself doesn't have formatting - it has neither a comma nor a dot.

It's when you convert it to a string that you'll get that. You can make sure you get a dot by specifying the invariant culture:

using System;
using System.Globalization;
using System.Threading;

class Test
{
    static void Main()
    {
        Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
        decimal d = 5.50m;
        string withComma = d.ToString();
        string withDot = d.ToString(CultureInfo.InvariantCulture);
        Console.WriteLine(withComma);
        Console.WriteLine(withDot);
    }
}
like image 150
Jon Skeet Avatar answered Oct 12 '22 07:10

Jon Skeet


As explained by Jon Skeet, you should specify the culture used to format the string:

var str = GetNumber().ToString(System.Globalization.CultureInfo.InvariantCulture);

It's a good practice to always use the ToString overload in which you specify the culture. Otherwise, .NET use the current thread Culture, which would write different strings to the output according to the locale of the PC...

like image 21
Eilistraee Avatar answered Oct 12 '22 06:10

Eilistraee


Locale-specific formatting?

http://en.wikipedia.org/wiki/File:DecimalSeparator.svg (Green equals a comma, so if you are calling ToString() on your decimal using the culture info of any of these locations, you will see a comma).

like image 1
Tim M. Avatar answered Oct 12 '22 06:10

Tim M.