Question

I've a double variable called totalCost and it's value is 1025. The result of calling a simple string.Format is the following:

?string.Format("{0}",totalCost)
"1,025"

My thousand separator is the dot while the decimal separator is the coma.

The weird part is the following:

?string.Format("{0:0.0}",totalCost)
"1,0"

Doesn't it should be 1025.0 (or 1,025.0)?

It seems that it converts the double in a string (giving "1.025") and then re-parse it without using my separator settings (interpreting it as 1-and-25-thousandths) and finally it formats the converted value.

EDIT: the thread culture is:

?System.Threading.Thread.CurrentThread.CurrentCulture
{it-IT}
Was it helpful?

Solution

You scenario is not what you think it is. I am 100% sure that your real value of totalCost is actually 1.025 (one and twenty five thousandths), because this is the only value that will produce both the same results that you have given.

This can be seen with the following code:

double d = 1.025; 
Console.WriteLine(string.Format(new System.Globalization.CultureInfo("it-IT"), "{0}",d));
//1,025
Console.WriteLine(string.Format(new System.Globalization.CultureInfo("it-IT"), "{0:0.0}",d));
//1,0

As you can see, both outputs match with yours. I would suggest you use a debugger to step through the code and see at which point the value is being changed. (perhaps you are dividing by 1000 somewhere along the line)

Direct Answer: There is no strange behaviour, the code is working exactly as expected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top