Home > Enterprise >  Output two numbers after comma with CultureInfo
Output two numbers after comma with CultureInfo

Time:04-26

Can someone provide the simple way to output float value in such format in C#:
dddddd,dd - exactly two digits after comma

I tried this:

number.ToString(CultureInfo.CreateSpecificCulture("uk-UA"));

but I don't know how to print two digits after a comma (even if there will be only ",00").

Optionally:
I also need to print numbers in this format:
d,ddd,ddd.dd

CodePudding user response:

Try to use this format string: "0.00".

using System.Globalization;

var data = new[] {0, 1, 1.2, 1.234, 1.2345, 123456789.123123 };
var nfi = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();
nfi.NumberGroupSeparator = ",";

foreach (var item in data)
{
    // first format
    Console.Write(item.ToString("0.00", CultureInfo.CreateSpecificCulture("uk-UA")) "\t");

    // second optional question
    Console.WriteLine(item.ToString("#,0.00", nfi));
}

Output:

0,00
1,00
1,20
1,23
1,23
123,12
  •  Tags:  
  • c#
  • Related