在C#中,Math.Floor
和Math.Round
是两个用于处理数字舍入的不同方法。
1. Math.Floor
Math.Floor
方法返回小于等于指定数字的最大整数。简单来说,它将数字向下舍入到最接近的整数或指定的小数位数。
会将给定的数值向下舍入到最接近的整数。对于12.5,向下舍入就是12。然后通过类型转换 (int) 将结果转换为整数类型。
double num = 3.7;
double floorValue = Math.Floor(num); // floorValue will be 3
2. Math.Round
Math.Round
方法则用于将数字四舍五入到最接近的整数或指定的小数位数。
会将给定的数值进行四舍五入。默认情况下,当参数为double时,四舍五入的行为是根据具体实现定义的,但通常遵循“银行家舍入规则”(也称作四舍六入五取偶)。
对于12.5这个特定值,在大多数情况下会四舍五入到13。然后通过类型转换 (int) 将结果转换为整数类型。
double num = 3.7;
double roundValue = Math.Round(num); // roundValue will be 4
// Rounding to a specific number of decimal places
double numWithDecimals = 3.745;
double roundedToTwoDecimals = Math.Round(numWithDecimals, 2); // roundedToTwoDecimals will be 3.75
如果想明确指定是按照中间值向远离零的方向舍入(即标准的四舍五入),可以这样使用:
int result = (int)Math.Round(value, MidpointRounding.AwayFromZero);
3. Math.Floor与Math.Round完整示例
using System;
class Program
{
static void Main()
{
//向下取整
double value = 12.5;
int result = (int)Math.Floor(value);
Console.WriteLine(result); // 输出:12
// 四舍五入到两位小数
int result1 = (int)Math.Round(value);
Console.WriteLine(result1); // 输出:13
}
}
C#中,使用Math.Floor
方法来实现保留一位小数且不进位的操作。
float fBoneAge = 0.00f;
float roundedBoneAge = Math.Floor(fBoneAge * 10) / 10f; // 向下取整到最近的一位小数
// 输出结果
Console.WriteLine(roundedBoneAge);