.NET中Math.Floor()和Math.Truncate()的区别是什么?
当前回答
Math.Floor ():
它给出小于或等于给定数的最大整数。
Math.Floor(3.45) =3
Math.Floor(-3.45) =-4
Math.Truncate ():
它删除数字的小数点后几位并替换为零
Math.Truncate(3.45)=3
Math.Truncate(-3.45)=-3
从上面的例子中我们还可以看到,对于正数,下限和截断是相同的。
其他回答
试试这个。
Math.Floor() vs Math.Truncate()
Math.Floor(2.56) = 2
Math.Floor(3.22) = 3
Math.Floor(-2.56) = -3
Math.Floor(-3.26) = -4
Math.Truncate(2.56) = 2
Math.Truncate(2.00) = 2
Math.Truncate(1.20) = 1
Math.Truncate(-3.26) = -3
Math.Truncate(-3.96) = -3
还Math.Round ()
Math.Round(1.6) = 2
Math.Round(-8.56) = -9
Math.Round(8.16) = 8
Math.Round(8.50) = 8
Math.Round(8.51) = 9
math.floor ()
返回小于或等于指定数字的最大整数。 MSDN system.math.floor
math.truncate ()
计算一个数的积分部分。 MSDN system.math.truncate
数学。楼层四舍五入,马斯。天花板来了,还有数学。将回合截断至零。因此,数学。截断就像数学。正数的地板,和数学一样。负数的上限。这是参考资料。
为了完整起见,请使用数学。四舍五入到最接近的整数。如果这个数字恰好在两个整数的中间,那么它就会四舍五入到偶数。参考。
参见:暗黑和平的答案。强烈推荐!
一些例子:
Round(1.5) = 2
Round(2.5) = 2
Round(1.5, MidpointRounding.AwayFromZero) = 2
Round(2.5, MidpointRounding.AwayFromZero) = 3
Round(1.55, 1) = 1.6
Round(1.65, 1) = 1.6
Round(1.55, 1, MidpointRounding.AwayFromZero) = 1.6
Round(1.65, 1, MidpointRounding.AwayFromZero) = 1.7
Truncate(2.10) = 2
Truncate(2.00) = 2
Truncate(1.90) = 1
Truncate(1.80) = 1
以下是MSDN对以下内容的描述:
Math.Floor, which rounds down towards negative infinity. Math.Ceiling, which rounds up towards positive infinity. Math.Truncate, which rounds up or down towards zero. Math.Round, which rounds to the nearest integer or specified number of decimal places. You can specify the behavior if it's exactly equidistant between two possibilities, such as rounding so that the final digit is even ("Round(2.5,MidpointRounding.ToEven)" becoming 2) or so that it's further away from zero ("Round(2.5,MidpointRounding.AwayFromZero)" becoming 3).
下面的图表可能会有所帮助:
-3 -2 -1 0 1 2 3
+--|------+---------+----|----+--|------+----|----+-------|-+
a b c d e
a=-2.7 b=-0.5 c=0.3 d=1.5 e=2.8
====== ====== ===== ===== =====
Floor -3 -1 0 1 2
Ceiling -2 0 1 2 3
Truncate -2 0 0 1 2
Round (ToEven) -3 0 0 2 3
Round (AwayFromZero) -3 -1 0 2 3
请注意,Round比它看起来强大得多,因为它可以舍入到特定的小数点后数位。其他的都是0小数。例如:
n = 3.145;
a = System.Math.Round (n, 2, MidpointRounding.ToEven); // 3.14
b = System.Math.Round (n, 2, MidpointRounding.AwayFromZero); // 3.15
对于其他函数,你必须使用乘除技巧来达到相同的效果:
c = System.Math.Truncate (n * 100) / 100; // 3.14
d = System.Math.Ceiling (n * 100) / 100; // 3.15
Math.Floor ():
它给出小于或等于给定数的最大整数。
Math.Floor(3.45) =3
Math.Floor(-3.45) =-4
Math.Truncate ():
它删除数字的小数点后几位并替换为零
Math.Truncate(3.45)=3
Math.Truncate(-3.45)=-3
从上面的例子中我们还可以看到,对于正数,下限和截断是相同的。
推荐文章
- Nuget连接尝试失败“无法为源加载服务索引”
- 我如何使一个方法的返回类型泛型?
- 如何获取正在执行的程序集版本?
- AutoMapper vs valueinjector
- 什么是.NET程序集?
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- 函数应该返回空对象还是空对象?
- 如何转换日期时间?将日期时间
- Numpy Max vs amax vs maximum
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 转换为值类型'Int32'失败,因为物化值为空
- c#中有任何连接字符串解析器吗?
- MSBuild路径
- c#和Java的主要区别是什么?
- 在c#中创建一个特定时区的DateTime