views:

61

answers:

4

Hello,

I would like to change decimal point to another character in C#. I have a double variable value and when I use the command:

Console.WriteLine(value.ToString()); // output is 1,25

I know I can do this:

Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("en-GB"))); // output is 1.25

but I don't like it very much because it's very long and I need it quite often in my program.

Is there a shorter version for setting "decimal point" really as point and not comma as is in my culture is usual?

A: 

The following article axplains how to set the culture in the current thread:

http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.currentculture%28VS.71%29.aspx

spender
+1  A: 

Perhaps I'm misunderstanding the intent of your question, so correct me if I'm wrong, but can't you apply the culture settings globally once, and then not worry about customizing every write statement?

Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
womp
Well, I don't need it in the whole program I need it to fit the format of PathGeometry in WPF where the decimal points are expected. But it turns out that this solution doesn't hurt anything else. Thank you!
MartyIX
+3  A: 

Create an extension method?

Console.WriteLine(value.ToGBString());

// ...

public static class DoubleExtensions
{
    public static ToGBString(this double value)
    {
        return value.ToString(CultureInfo.GetCultureInfo("en-GB"));
    }
}
LukeH
I like the solution!
MartyIX
A: 

You can change the decimal separator by changing the culture used to display the number. Beware however that this will change everything else about the number (eg. grouping separator, grouping sizes, number of decimal places). From your question, it looks like you are defaulting to a culture that uses a comma as a decimal separator.

To change just the decimal separator without changing the culture, you can modify the NumberDecimalSeparator property of the current culture's NumberFormatInfo.

Thread.CurrentCulture.NumberFormat.NumberDecimalSeparator = ".";

This will modify the current culture of the thread. All output will now be altered, meaning that you can just use value.ToString() to output the format you want, without worrying about changing the culture each time you output a number.

(Note that a neutral culture cannot have its decimal separator changed.)

adrianbanks