Home
VB.NET
Math.Truncate Method, Cast Double to Integer
Updated 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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Aug 6, 2021 (image).
Home
Changes
© 2007-2025 Sam Allen