【C# 】Math.Floor与Math.Round的使用

在C#中,Math.FloorMath.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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wangnaisheng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值