0

I need to format ints and floats to string.

If it's float, I need , to be decimal separator. And . must be thousand separator.

Also, I need to complete remaining decimals with 0. Some examples:

float:
45,3: 000.045,30
125: 000.125,00
83560.195: 083.560,19

int:
45: 000.045
5789: 005.789

I managed to format thousands with "{0:#,0}" but I still can't find how to format decimals and how to properly pad keeping separators.

This must be done regardless of configured culture :/

Hikari
  • 3,797
  • 12
  • 47
  • 77
  • 1
    Have you tried googling this ..? there are a lot of different ways to do this.. here is a previous `SO` posting that can give you many answers hints and a direction that you can take. http://stackoverflow.com/questions/105770/net-string-format-to-add-commas-in-thousands-place-for-a-number – MethodMan Jan 13 '15 at 15:45
  • I think you should use http://msdn.microsoft.com/en-us/library/system.iformatprovider.aspx – Ahmet Arslan Jan 13 '15 at 15:49
  • Thanks guys. I was googling it and was able to learn part of the solution, but was unable to find the part I asked here. – Hikari Jan 14 '15 at 12:32

2 Answers2

4

This works with the given examples:

NumberFormatInfo numberFormat = new NumberFormatInfo
{
    NumberDecimalSeparator=",",
    NumberGroupSeparator="."
};

string formatFloat(float f)
{
    return f.ToString("0####,0.00",numberFormat);
}

string formatInt(int i)
{
    return i.ToString("0####,0",numberFormat);
}
Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
  • Good solution, and looks independent on current culture. If one wants to reuse the format info object, one can use `static readonly NumberFormatInfo numberFormat = NumberFormatInfo.ReadOnly(new NumberFormatInfo { NumberDecimalSeparator = ",", NumberGroupSeparator = ".", });` to be on the very safe side. – Jeppe Stig Nielsen Jan 13 '15 at 16:14
1

You can set the culture to a European culture, and format:

string.Format(new CultureInfo("de-DE"), "{0:000,000.00}", num).Dump();
Dave Bish
  • 19,263
  • 7
  • 46
  • 63