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
.
Here we introduce four Doubles and then call Math.Truncate
on them. Their fractional parts are removed—their signs and integral parts are kept.
Math.Truncate
and print the results to the console with Console.WriteLine
.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
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.
Math.Truncate
is a better choice. It also makes explicit the goal of the operation.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.