Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does (int)myDouble ever differ from (int)Math.Truncate(myDouble)?

Tags:

c#

.net

math

Does (int)myDouble ever differ from (int)Math.Truncate(myDouble)?

Is there any reason I should prefer one over the other?

like image 558
mpen Avatar asked Jun 17 '12 17:06

mpen


People also ask

What is math truncate?

trunc() The Math. trunc() function returns the integer part of a number by removing any fractional digits.

What is the difference between truncate and floor?

Math. Floor rounds down, Math. Ceiling rounds up, and Math. Truncate rounds towards zero.

How do you truncate a number in C#?

Truncate() Method in C# This method is used to get the integral digits of the specified Decimal by discarding any fractional digits. This method rounds the specified value to the nearest whole number by removing the digits after the decimal point.


1 Answers

Math.Truncate is intended for when you need to keep your result as a double with no fractional part. If you want to convent it to an int, just use the cast directly.

Edit: For reference, here is the relevant documentation from the “Explicit Numeric Conversions Table”:

When you convert from a double or float value to an integral type, the value is truncated.

like image 52
Douglas Avatar answered Oct 04 '22 03:10

Douglas