Search code examples
c#number-formatting

need to ignore decimal places from string if decimal places is .00


Hello Everyone I want to ignore this .00 from string number. Below is my sample input and need output. I have tried this code. String.Format ("{0: n}", Amount) but problem in this code.

If value is 10000. 00.
My code will convert it into "10, 000.00"
but I need only "10, 000".

Please help me to fix the issue.

More examples:

10000.00  -> "10,000"
10000.12  -> "10,000.12"
10000.1   -> "10,000.10"

Solution

  • So you have some kind of money: we output cents if and only if we have them:

      10000.00  -> 10,000    (no cents; exactly 10000)
      10000.003 -> 10,000    (no cents; still exactly 10000) 
      10000.1   -> 10,000.10 (ten cents)
      10000.12  -> 10,000.12 (twelve cents)
      10000.123 -> 10,000.12 (still twelve cents)
    

    The last three cases we can format out as "#,0.00" and the first two will be correct with "#,0" format string. The only problem is to distinguish the cases.

    We can try using Math.Round() for this

      string result = d.ToString(Math.Round(d) != Math.Round(d, 2) ? "#,0.00" : "#,0");
    

    Demo:

    decimal[] tests = new decimal[] {
      10000.00m,
      10000.003m,
      10000.10m,
      10000.12m,
      10000.123m,
    };
    
    string report = string.Join(Environment.NewLine, tests
      .Select(d => 
         $"{d,-10} -> {d.ToString(Math.Round(d) != Math.Round(d, 2) ? "#,0.00" : "#,0")}"));
    
    Console.Write(report);
    

    Outcome:

    10000.00   -> 10,000
    10000.003  -> 10,000
    10000.10   -> 10,000.10
    10000.12   -> 10,000.12
    10000.123  -> 10,000.12