Question

I thought this was simple; the .Net Framework has so many functions for formatting a number exactly as you want, but still, I haven't been able to make this work.

The problem: display a number according to the European rules, so with "." for a thousands separator and "," for a decimal separator, but without also fixing the number of decimals.

So, for example, if I have 1234, that is supposed to print as "1.234", and 1234.5 is supposed to print as "1.234,5". But none of the formats I've tried do exactly that!

Examples: suppose that ci is a CultureInfo with the correct settings, then

num.ToString(ci)      -> "1234,5"    decimals OK, but no thousands separator
num.ToString("G", ci) -> "1234,5"    same as above
num.ToString("N", ci) -> "1.234,50"  thousands separator OK, but too many decimals

and so on. Similar with using a NumberFormatInfo instead of a CultureInfo, or trying String.Format or Convert.ToString. Anybody have any other ideas?

Was it helpful?

Solution

You can hardcode format string like this

num.ToString("###,###,###.####");

this will output with respect tu Current thread culture info. If you have european culture you will get "." as thousands separator. And this will output up to 4 decimals that are not equal 0. You can increase number of decimals and number of groups if you have larger numbers or need greater precison. But, not sure if there is a more elegant way...

OTHER TIPS

maybe you looking for this:

number.ToString("#,##0.##", customCulture);

Example of use:

double first = 12345.67;
double second = 1234567;
var customCulture = (System.Globalization.CultureInfo)
    System.Globalization.CultureInfo.CurrentCulture.Clone();
customCulture.NumberFormat.NumberDecimalSeparator = ",";
customCulture.NumberFormat.NumberGroupSeparator = ".";
Console.WriteLine("First :    " + first.ToString("#,##0.##", customCulture));
Console.WriteLine("Second: "   + second.ToString("#,##0.##", customCulture));

without define exact culture info you can not guarantee the same result in any culture.

This is result I get in console:

First :    12.345,67
Second: 1.234.567
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top