Difference between Math.Floor() and Math.Truncate(

2018-12-31 20:02发布

What is the difference between Math.Floor() and Math.Truncate() in .NET?

标签: .net math
10条回答
妖精总统
2楼-- · 2018-12-31 20:20

They are functionally equivalent with positive numbers. The difference is in how they handle negative numbers.

For example:

Math.Floor(2.5) = 2
Math.Truncate(2.5) = 2

Math.Floor(-2.5) = -3
Math.Truncate(-2.5) = -2

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:

float myFloat = 4.5;
Console.WriteLine( Math.Round(myFloat) ); // writes 4
Console.WriteLine( Math.Round(myFloat, 0, MidpointRounding.AwayFromZero) ) //writes 5
Console.WriteLine( myFloat.ToString("F0") ); // writes 5
查看更多
荒废的爱情
3楼-- · 2018-12-31 20:24

Math.Floor rounds down, Math.Ceiling rounds up, and Math.Truncate rounds towards zero. Thus, Math.Truncate is like Math.Floor for positive numbers, and like Math.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!

查看更多
永恒的永恒
4楼-- · 2018-12-31 20:25

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.

查看更多
永恒的永恒
5楼-- · 2018-12-31 20:27

Some examples:

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
查看更多
永恒的永恒
6楼-- · 2018-12-31 20:29

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

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

In addition 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
查看更多
栀子花@的思念
7楼-- · 2018-12-31 20:30

Math.Floor() rounds toward negative infinity

Math.Truncate rounds up or down towards zero.

For example:

Math.Floor(-3.4)     = -4
Math.Truncate(-3.4)  = -3

while

Math.Floor(3.4)     = 3
Math.Truncate(3.4)  = 3
查看更多
登录 后发表回答