VB.NET Math.Truncate Method, Cast Double to Integer

Use Math.Truncate to remove the fractional parts of numbers. See how a Double is cast to an Integer.

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.

First: 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.

VB.NET program that uses Math.Truncate, Double to Integer casts 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 Output :::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.Math.Round
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to