标签云

微信群

扫码加入我们

WeChat QR Code

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


e.g. Math.Floor(5.4) = 5 Math.Truncate(5.4) = 5

2018年07月19日57分57秒

you really need this after 10 years odd? lol

2018年07月19日57分57秒

why after 10 years is there a bounty? there are many answers already. is there something i'm missing here?

2018年07月19日57分57秒

Chris, I suggest you fix your description of Round, there's two ways to round (AwayFromZero and ToEven) and it doesn't round to the nearest integer since it can do fractional rounding as well.

2018年07月19日57分57秒

So just a short add on to the original question - what is the difference between Math.Truncate and just casting a decimal or double to int? wouldn't it also just round towards zero?

2018年07月19日57分57秒

When does (int)myDouble differ from (int)Math.Truncate(myDouble)?

2018年07月19日57分57秒

What is (int) equal to in Math class?

2018年07月19日57分57秒

Pax, I think you've got a mistake with: Round(AwayFromZero) -3 -2 1 2 3 Math.Round(-1.2, MidpointRounding.AwayFromZero) == -1 Math.Round(0.3, MidpointRounding.AwayFromZero)==0.0 etc..

2018年07月19日57分57秒

Thanks, dtroy, I've never had a need to use that mode and, while I documented it correctly if the text, I totally got the examples wrong. Hopefully that's fixed now.

2018年07月19日57分57秒

Sorry to comment on such an old question but I have to ask: How can you round "ToEven" to two decimal places? Surely odd and even apply only to integers?

2018年07月19日57分57秒

Richiban, think of even as a property of the final digit in the rounded number, not as meaning the entire number must be a multiple of two. By the way, sorry it took so long to get back to you, hope you weren't just sitting around waiting for my response :-)

2018年07月19日57分57秒

The OP asked about the difference between Floor() and Truncate(), not Floor() and Round().

2018年07月19日57分57秒