2

I have 2 double values

double d1 = 3456786.065343

double d2 = 4848484.000000

I have to format the numbers only if value after decimal is 0, round up to two zero decimal places e.g 4848484.00

If numbers after decimal is not zero then dont apply any formatting E.g 3456786.065343

3 Answers3

4

You can check if a decimal is an integer or not, if a decimal holds some digits other than 0 after decimal then it is not an integer while otherwise would be true

First case:

decimal d = 4848484.000000M;
        if((d % 1) == 0)
        {
         // prints 4848484.00
          Console.WriteLine(decimal.Round(d, 2, MidpointRounding.AwayFromZero)); 
        }
        else
        {
            Console.WriteLine(d.ToString());
        }

Second case:

decimal d1 = 3456786.065343M;
            if((d1 % 1) == 0)
            {
              Console.WriteLine(decimal.Round(d1, 2, MidpointRounding.AwayFromZero)); 
            }
            else
            {
                //prints 3456786.065343
                Console.WriteLine(d1.ToString()); 
            }

so if a decimal is like 3456786.065343 this will print it as it is.

and if decimal is like 4848484.000000 this will print 4848484.00

Ambrish Pathak
  • 3,813
  • 2
  • 15
  • 30
4

checking if a number has decimal floating points is fairly simple:

private void Foo()
        {
            double d2 = 4848484.000000;

            if (d2 - Math.Round(d2) != 0)
            {
                Console.WriteLine(d2.ToString());
            }

            else
            {
                Console.WriteLine(d2.ToString("0.00####"));
            }
        }
Jonathan Applebaum
  • 5,738
  • 4
  • 33
  • 52
0

If you're just looking to format the numbers for display, use a format string of 0.00########. This will display at least 2 decimal places.

var s1 = d1.ToString("0.00####"):
Andy Lamb
  • 2,151
  • 20
  • 22