Home > OS >  Round numbers (including integers) to two decimal places and display them up to two decimal places.
Round numbers (including integers) to two decimal places and display them up to two decimal places.

Time:11-08

I have declared some values as doubles:

double mean;
double median;

Since the mean after the calculation is a whole number, it is showing without any decimal value. But I need 2 decimal values.
eg:- if the mean is 255, I need to show it as 255.00.
How to achieve this?

What I have tried: Round(mean,2)

Still showing 255

Need 255.00

Need the same for the numbers from the data file too. Need to show the whole number as a decimal number with 2 precision.

CodePudding user response:

try this:

  decimal a = 255;
  var result = Math.Round(a, 2).ToString("0.00");

CodePudding user response:

There are separate 2 issues here:

  1. Mathematically rounding a double value to 2 decimal places. This will keep 255, and 255.01 as is, but convert e.g. 123.123 to 123.12.
  2. Format a string with 2 fixed decimal places. This will add e.g. ".00" if the value is an integer.

Both are demonstrated below:

using System;

namespace ConsoleApp1
{
    internal class Program
    {

        static void test(double d)
        {
            // Mathematically round to 2 decimal places
            double d2 = Math.Round(d, 2);
            // Use d2 if you need a double value with 2 decimal places.

            // Format string with 2 fixed decimal places:
            string str = d.ToString("0.00");

            // Write the formatted string:
            Console.WriteLine(str);
        }

        static void Main(string[] args)
        {
            test(255);
            test(255.01);
            test(123.123);
        }
    }
}

Output:

255.00
255.01
123.12
  • Related