skip to Main Content

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?

2

Answers


  1. 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
    
    Login or Signup to reply.
  2. You can use the custom format specifier #, which only returns decimal digits if they exist in the number, both before the decimal point and after.

    For example, for de-DE culture:

    Console.WriteLine(1254812.45.ToString("#,###.###", CultureInfo.GetCultureInfo("de-DE")));
    Console.WriteLine(1254812.0.ToString("#,###.###", CultureInfo.GetCultureInfo("de-DE")));
    

    Output

    1.254.812,45
    1.254.812
    

    dotnetfiddle

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search