MathF.Round() Method in C# with Examples | Set – 1
Last Updated :
04 Apr, 2019
In C#, MathF.Round() is a MathF class method which is used to round a value to the nearest integer or to the particular number of fractional digits. This method can be overloaded by changing the number and type of arguments passed. There are 4 methods in the overload list of the MathF.Round() method.
- MathF.Round(Single) Method
- MathF.Round(Single, Int32) Method
- MathF.Round(Single, Int32, MidpointRounding) Method
- MathF.Round(Single, MidpointRounding) Method
Here, we will discuss the first two methods.
MathF.Round(Single) Method
This method rounds a single-precision floating-point value to the nearest integer value.
Syntax: public static float Round (float x);
Here, x is a singlefloating-point number which is to be rounded. Type of this parameter is System.Single.
Return Type:It returns the integer nearest to x and return type is System.Single.
Note: In case if the fractional component of x is halfway between two integers, one of which is even and the other odd, then the even number is returned.
Example:
using System;
class Geeks {
static void Main( string [] args)
{
float dx1 = 12.434565f;
Console.WriteLine( "Rounded value of " + dx1 +
" is " + MathF.Round(dx1));
float dx2 = 12.634565f;
Console.WriteLine( "Rounded value of " + dx2 +
" is " + MathF.Round(dx2));
}
}
|
Output:
Rounded value of 12.43456 is 12
Rounded value of 12.63457 is 13
MathF.Round(Single, Int32) Method
This method rounds a single precision floating-point value to a specified number of fractional digits.
Syntax: public static float Round (float x, int digits);
Parameters:
x: A single floating-point number which is to be rounded. Type of this parameter is System.Single.
y: It is the number of fractional digits in the returned value. Type of this parameter is System.Int32.
Return Type: It returns the integer nearest to x which contains a number of fractional digits equal to y and return type is System.Single.
Exception: This method will give ArgumentOutOfRangeException if the value of y is less than 0 or greater than 15.
Example:
using System;
class Geeks {
static void Main( string [] args)
{
float dx1 = 12.434565f;
Console.WriteLine( "Rounded value of " + dx1 +
" is " + MathF.Round(dx1, 4));
float dx2 = 12.634565f;
Console.WriteLine( "Rounded value of " + dx2 +
" is " + MathF.Round(dx2, 2));
}
}
|
Output:
Rounded value of 12.43456 is 12.4346
Rounded value of 12.63457 is 12.63
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...