Home > OS >  How can I cut value after point? I mean: double a = 4.33333333 I need print it like this: 4.33?
How can I cut value after point? I mean: double a = 4.33333333 I need print it like this: 4.33?

Time:11-01

first I want to apologize for my English, but I have one question: in the code below I want to cut some values after the point, so ho can I do it? BUT Without using any Built methods!

static void Main(string[] args)
{
    int[] array = { 6, 2, 3, 2, 12, 1 };
    double arithmethicAverage;
    arithmethicAverage = ArithmethicAverage(array);
    Console.WriteLine($"Arithmetic average of array is: {arithmethicAverage} "); // ==> 4,333333333333333 but i need to print:-->  4,33
}

public static double ArithmethicAverage(int[] array)
{
    double result = 0;
    for (int i = 0; i < array.Length; i  )
    {
        result  = array[i];
    }
    result /= array.Length;
    return result;
}

CodePudding user response:

If you just want to show it you can use ToString() extension method like this :

arithmethicAverage.ToString("0.00")

For more information you can search about string formatters in C#.

CodePudding user response:

You can use the same format and precision speciriers you'd use in ToString() for example

{arithmethicAverage:N2}

You can specify a custom format string too :

{arithmethicAverage:0.00}

The precision specifier doesn't round :

The precision specifier controls the number of digits in the string representation of a number. It does not round the number itself.

CodePudding user response:

If you don't want to use the built-in methods, this is one of the solutions.

var a = 4.33333333d;
Console.WriteLine(a - a % 0.1);    // 4.3
Console.WriteLine(a - a % 0.01);   // 4.33
Console.WriteLine(a - a % 0.001);  // 4.333
Console.WriteLine(a - a % 0.0001); // 4.3333
  •  Tags:  
  • c#
  • Related