Reputation: 151
Given number is 282100
. I want to display above number like 282.100,00
I am using
String.Format("{0:n}", number)
but I'm getting result like this 282,100.00
.
expected=282.100,00
.
Is there any way to do this in C#?
Upvotes: 0
Views: 1301
Reputation: 37070
You can customize the format by providing a new IFormatProvider:
var num = 282100;
// Output using a custom formatter:
Console.WriteLine(num.ToString("N",
new NumberFormatInfo{ NumberDecimalSeparator = ",", NumberGroupSeparator = "."}));
// Or if you want to save the formatted string:
var str = String.Format(new NumberFormatInfo {NumberDecimalSeparator = ",",
NumberGroupSeparator = "."}, "{0:N}", num);
Console.WriteLine(str);
Upvotes: 0
Reputation: 70701
If your current culture does not format the number the way you want, you have a couple of options (at least):
CultureInfo
that does format the number the way you wantNumberFormatInfo
that uses the format you wantIn general, I'd say the first option is better. After all, if you have a need to format the number in a specific way, chances are it's because you are doing it for some specific culture. So the best way in that case is to just get the correct CultureInfo
object (i.e. by using CultureInfo.GetCultureInfo()
) and use that as the IFormatProvider
for the formatting.
If for some reason it's not always clear which specific CultureInfo object to get, then you can do it the second way. For example:
decimal number = 282100;
NumberFormatInfo numberFormatInfo =
(NumberFormatInfo)CultureInfo.CurrentCulture.NumberFormat.Clone();
numberFormatInfo.NumberDecimalSeparator = ",";
numberFormatInfo.NumberGroupSeparator = ".";
string text = string.Format(numberFormatInfo, "{0:n}", number);
This particular example allows you to start with a known formatter and then modify it per your specific needs.
Finally, if you believe your current culture should be formatting the number the way you want but it isn't doing that, then it is best to figure out why it's not doing that, rather than overriding the current culture. Usually, you want to use the default formatting for any text displayed to the user or received from the user, so that the program works correctly regardless of culture.
Upvotes: 1
Reputation: 5600
You can create your own number format and use that to get desired results. Something like this:
NumberFormatInfo customFormat = new NumberFormatInfo(); ;
customFormat.NumberGroupSeparator = ".";
customFormat.NumberDecimalSeparator = ",";
customFormat.NumberGroupSizes = new int[1]{3};
decimal someNumber = 123456789.123m;
string number = someNumber.ToString("N",customFormat);
Upvotes: 0