What is the difference between Math.Floor()
and Math.Truncate()
in .NET?
相关问题
- Generic Generics in Managed C++
- How to Debug/Register a Permanent WMI Event Which
- 'System.Threading.ThreadAbortException' in
- Bulk update SQL Server C#
- Should I use static function in c# where many call
They are functionally equivalent with positive numbers. The difference is in how they handle negative numbers.
For example:
MSDN links: - Math.Floor Method - Math.Truncate Method
P.S. Beware of Math.Round it may not be what you expect.
To get the "standard" rounding result use:
Math.Floor
rounds down,Math.Ceiling
rounds up, andMath.Truncate
rounds towards zero. Thus,Math.Truncate
is likeMath.Floor
for positive numbers, and likeMath.Ceiling
for negative numbers. Here's the reference.For completeness,
Math.Round
rounds to the nearest integer. If the number is exactly midway between two integers, then it rounds towards the even one. Reference.See also: Pax Diablo's answer. Highly recommended!
Math.Floor()
: Returns the largest integer less than or equal to the specified double-precision floating-point number.Math.Round()
: Rounds a value to the nearest integer or to the specified number of fractional digits.Some examples:
math.floor()
Returns the largest integer less than or equal to the specified number.
MSDN system.math.floor
math.truncate()
Calculates the integral part of a number.
MSDN system.math.truncate
In addition Math.Round()
Math.Floor()
rounds toward negative infinityMath.Truncate
rounds up or down towards zero.For example:
while