I am developing a function that, passing a number, formats it with the thousands separators and the decimal separators (if it has them) taking into account the cultural information of the user in question, and I have the following problem:
I have this piece of code:
public string FormatearNumero(object Num)
{
CultureInfo Culture = new CultureInfo("en-EN", false);
NumberStyles NStyle = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | NumberStyles.AllowLeadingSign;
string Numero = Num.ToString();
if (decimal.TryParse(Numero, NStyle, Culture, out decimal result))
{
if (result == 0)
return Numero;
Numero = result.ToString("###" + Culture.NumberFormat.NumberGroupSeparator + "###" + Culture.NumberFormat.NumberDecimalSeparator + "####", Culture);
}
return Numero;
}
To format the number I use the typical one .ToString("###.###,###")
but in this case applying in the thousands separators the one that corresponds to it by cultural reference and the same for the decimal separator.
result.ToString("###" + Culture.NumberFormat.NumberGroupSeparator + "###" + Culture.NumberFormat.NumberDecimalSeparator + "####", Dades.Culture)
Applying this portion of code with culture en-EN
I get the following results:
//Culture.NumberFormat.NumberGroupSeparator tiene el valor ','
//Culture.NumberFormat.NumberDecimalSeparator tiene el valor '.'
FormatearNumero("-98745618451.6513") --> "-98,745,618,451.6513"
Instead, when I change the cultural reference and put it, for example, es-ES
the following happens:
//Culture.NumberFormat.NumberGroupSeparator tiene el valor '.'
//Culture.NumberFormat.NumberDecimalSeparator tiene el valor ','
FormatearNumero("-98745618451,6513") --> "-98745618451,6513"
It does not apply the formats correctly for some cultures, but for others it does.
I have tried to search for information about it but I have not found anything, and on the pages of Microsoft
they do not indicate anything to take into account when applying these formats.
Could someone tell me where the problem could be?
The problem you are having is with the custom format you are using. You assumed that in the format you had to put the separator that corresponded to the chosen culture (for example,
.
as a thousands separator in Spanish,,
as a thousands separator in English).As explained in Custom Numeric Format Strings , the
.
in the format always acts as a decimal separator, and the always acts as,
a group separator:That is, in the format you must always use the same characters as the group separator and decimal. Then it is the culture that you use when formatting the number that will indicate if the separator is one or the other in the output.
In short, your format string should be the following regardless of the culture you are going to use:
"###,###.####"
. That way you will format it correctly regardless of the culture used: