Does (int)myDouble
ever differ from (int)Math.Truncate(myDouble)
?
Is there any reason I should prefer one over the other?
trunc() The Math. trunc() function returns the integer part of a number by removing any fractional digits.
Math. Floor rounds down, Math. Ceiling rounds up, and Math. Truncate rounds towards zero.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With