Urmați aceste linkuri pentru descrierile MSDN ale:
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).
Diagrama și tabelul de mai jos vă pot ajuta:
-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
Rețineți că Round
este mult mai puternic decât pare, pur și simplu pentru că poate rotunji la un anumit număr de zecimale. Toți ceilalți rotunjește la zero zecimale întotdeauna. De exemplu:
n = 3.145;
a = System.Math.Round (n, 2, MidpointRounding.ToEven); // 3.14
b = System.Math.Round (n, 2, MidpointRounding.AwayFromZero); // 3.15
Cu celelalte funcții, trebuie să folosiți trickery multiplica / împărți pentru a obține același efect:
c = System.Math.Truncate (n * 100) / 100; // 3.14
d = System.Math.Ceiling (n * 100) / 100; // 3.15