在C#中, MathF.Round()是MathF类方法,用于将值四舍五入到最接近的整数或小数位数。可以通过更改传递的参数的数量和类型来重载此方法。 MathF.Round()方法的重载列表中有4种方法。
- MathF.Round(Single)方法
- MathF.Round(Single,Int32)方法
- MathF.Round(Single,Int32,MidpointRounding)方法
- MathF.Round(Single,MidpointRounding)方法
在这里,我们将讨论前两种方法。
MathF.Round(Single)方法
此方法将单精度浮点值舍入为最接近的整数值。
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.
注意:如果x的小数部分位于两个整数的中间,其中一个为偶数,另一个为奇数,则返回偶数。
例子:
// C# program to demonstrate the
// MathF.Round(Single) method
using System;
class Geeks {
// Main method
static void Main(string[] args)
{
// Case-1
// A float value whose fractional part is
// less than the halfway between two
// consecutive integers
float dx1 = 12.434565f;
// Output value will be 12
Console.WriteLine("Rounded value of " + dx1 +
" is " + MathF.Round(dx1));
// Case-2
// A float value whose fractional part is
// greater than the halfway between two
// consecutive integers
float dx2 = 12.634565f;
// Output value will be 13
Console.WriteLine("Rounded value of " + dx2 +
" is " + MathF.Round(dx2));
}
}
Rounded value of 12.43456 is 12
Rounded value of 12.63457 is 13
MathF.Round(Single,Int32)方法
此方法将单个精度浮点值舍入为指定数量的小数位数。
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.
返回类型:返回最接近x的整数,该整数包含等于y的小数位数,返回类型为System.Single 。
异常:如果y的值小于0或大于15,则此方法将提供ArgumentOutOfRangeException。
例子:
// C# program to demonstrate the
// MathF.Round(Single, Int32) Method
using System;
class Geeks {
// Main method
static void Main(string[] args)
{
// float type
float dx1 = 12.434565f;
// using method
Console.WriteLine("Rounded value of " + dx1 +
" is " + MathF.Round(dx1, 4));
// float type
float dx2 = 12.634565f;
// using method
Console.WriteLine("Rounded value of " + dx2 +
" is " + MathF.Round(dx2, 2));
}
}
Rounded value of 12.43456 is 12.4346
Rounded value of 12.63457 is 12.63