Math.Truncate Method, Cast Double to Integer
This page was last reviewed on Aug 6, 2021.
Dot Net Perls
Math.Truncate. Consider a number like 1.234. It has an integral part—the value 1—and also a fractional part. With Math.Truncate we eliminate the fractional part.
For negative numbers, Math.Truncate also just removes the fractional part. This is different from the behavior of Math.Round, Ceiling, or Floor.
An example program. Here we introduce four Doubles and then call Math.Truncate on them. Their fractional parts are removed—their signs and integral parts are kept.
Detail We use Math.Truncate and print the results to the console with Console.WriteLine.
Then We use implicit casts to Integer. For small doubles (which fit in the integer bytes) the result is the same as Math.Truncate.
Module Module1 Sub Main() Dim value1 As Double = 1.234 Dim value2 As Double = 1.999 Dim value3 As Double = -1.999 Dim value4 As Double = -1.234 Console.WriteLine(":::TRUNCATE:::") ' Use Math.Truncate to truncate the double values. Console.WriteLine(Math.Truncate(value1)) Console.WriteLine(Math.Truncate(value2)) Console.WriteLine(Math.Truncate(value3)) Console.WriteLine(Math.Truncate(value4)) Console.WriteLine(":::CAST:::") ' Use implicit Integer casts to truncate the double values. Dim value1Cast As Integer = value1 Dim value2Cast As Integer = value2 Dim value3Cast As Integer = value3 Dim value4Cast As Integer = value4 Console.WriteLine(value1Cast) Console.WriteLine(value2Cast) Console.WriteLine(value3Cast) Console.WriteLine(value4Cast) End Sub End Module
:::TRUNCATE::: 1 1 -1 -1 :::CAST::: 1 2 -2 -1
Some notes. If a program uses smaller numbers only, then casting to Integer is acceptable and may be more efficient. But for large numbers, this can cause an overflow.
So In most cases Math.Truncate is a better choice. It also makes explicit the goal of the operation.
A summary. Like Math.Round, Ceiling and Floor, Math.Truncate changes the fractional part of a number. Its affects negative numbers in the same way as positive numbers.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 6, 2021 (image).
© 2007-2024 Sam Allen.