Format decimal value to currency with optional precision

I have c# project. I use ToString("N", CultureInfo.CurrentCulture) for format double value and the result is like 1.254.812,45 .There is no problem. But when I have no precision I don’t want to display 1.254.812,00. I want to display only 1.254.812 . How can I do it?

>Solution :

I don’t know if there is a direct solution, but the Convert() method I developed provides a solution.

using System;
using System.Globalization;
                    
public class Program
{
    public static string Convert(string value)
    {
        if(value.Split('.')[1].Equals("00"))
            return value.Split('.')[0];
        return value;
    }
    
    public static void Main()
    {
        double[] inputs = {1254812.00, 1254812.45};
        string[] results = {inputs[0].ToString("N", CultureInfo.CurrentCulture), inputs[1].ToString("N", CultureInfo.CurrentCulture)};
        Console.WriteLine("{0}\t{1}", Convert(results[0]), Convert(results[1]));
    }
}

This code produces the following output:

1,254,812    1,254,812.45

Leave a Reply