C# - Math.Round() Method with Example

In this tutorial, we will learn about the C# Math.Round() method with its definition, usage, syntax, overload, and example. By Nidhi Last updated : March 29, 2023

C# Math.Round() Method

The Math.Round() method is used to round off floating-point numbers to the nearest integer value. This method is overloaded 8 times.

Overloads

Decimal     Math.Round(Decimal)
Double      Math.Round(Double)
Decimal     Math.Round(Decimal, Int32)
Decimal     Math.Round(Decimal, MidpointRounding)
Double      Math.Round(Double, Int32)
Double      Math.Round(Double, MidpointRounding)
Decimal     Math.Round(Decimal, Int32, MidpointRounding)
Double      Math.Round(Double, Int32, MidpointRounding)

Parameter(s)

Here we passed double and decimal values to round off given value according to the overloaded method.

Return Value

This method returns double or decimal values according to the overloaded method.

C# Example of Math.Round() Method

The source code to demonstrate the use of Round() method of Math class is given below. The given program is compiled and executed successfully.

using System;

class Sample {
  //Entry point of Program
  static public void Main() {
    double val = 0.0;
    decimal decVal = 0.0M;

    Console.WriteLine("Demonstration of Round Method: ");
    val = Math.Round(2.4);
    Console.WriteLine("Value : " + val);

    val = Math.Round(2.5);
    Console.WriteLine("Value : " + val);

    val = Math.Round(2.6);
    Console.WriteLine("Value : " + val);

    val = Math.Round(2.4567, 2);
    Console.WriteLine("Value : " + val);

    val = Math.Round(2.4567, 3);
    Console.WriteLine("Value : " + val);

    decVal = Math.Round(2.4567M, 2);
    Console.WriteLine("Decimal Value : " + decVal);

    decVal = Math.Round(2.4567M, MidpointRounding.AwayFromZero);
    Console.WriteLine("Decimal Value : " + decVal);
  }
}

Output

Demonstration of Round Method:
Value : 2
Value : 2
Value : 3
Value : 2.46
Value : 2.457
Decimal Value : 2.46
Decimal Value : 2
Press any key to continue . . .

C# Math Class Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.