Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Output two numbers after comma with CultureInfo

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").

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading