Xojo®'s API provides us with three ways to convert a decimal number to a whole number:
It rounds a Double to the nearest whole number.
Round( 18.35 )returns 18 while
Round( 18.55 )returns 19.
It returns the next lowest whole number.
Floor( 14.6 )returns 14 and
Floor( -14.6 )returns -15.
It returns the next highest whole number.
Ceil( 14.6 )returns 15 and
Ceil( -14.6 )return 14.
But if you only need to truncate a decimal number to its integer part, there is no out-of-the-box method. So let's implement our own truncate method.
If the number to truncate is positive then we'll use
Floor() and if the number is negative, we'll use
Ceil(). For the '
0' (zero) case, we'll just consider it as a positive number. Let's add the following code to a module as a public method:
Function Trunc(inValue As Double) As Double If inValue >= 0.0 Then Return Floor( invalue ) Else Return Ceil( inValue ) End If End Function
And you can use it like this:
Dim theWholeNumber As Double = Trunc( 1234.567 ) MsgBox Str( theWholeNumber )
While we're at it, let's extend the
Double data type with a
Double.Trunc() As Double method. So in the same module, create a new
Trunc() method defined like this:
Function Trunc(Extends extValue As Double) As Double If extValue >= 0.0 Then Return Floor( extValue ) Else Return Ceil( extValue ) End If End Function
Now you can use it like this:
Dim theDecimalNumber As Double = 1234.567 Dim theWholeNumber As Double = theDecimalNumber.Trunc MsgBox Str( theWholeNumber )
I wrote these methods as I needed to determine if a
Double was a whole number or not. For that purpose, I choose to compare the
Double number and its truncated counterpart. If they're equals, then this is a whole number. Otherwise, it's a decimal number.
Function IsWholeNumber(inValue As Double) As Boolean Return inValue.Equals( inValue.Trunc, 0 ) End Function
Double.IsWholeNumber() As Boolean syntax:
Function IsWholeNumber(Extends extValue As Double) As Boolean Return extValue.Equals( extValue.Trunc, 0 ) End Function
The use of
Equals() allows us to get rid of the "Performing a = comparison [...] can yield unexpected result [...]" warning. If you want, I leave it to you to implement a
IsOdd( Double ) As Boolean.
As always, Xojo® gives us the opportunity to expand its API with our own functionalities. In the same spirit, you can add a
IsOdd( Double ) As Boolean and a
Double.IsOdd() As Boolean and even transpose them to handle the
Single data type.
Next week, we'll continue to expand our customized framework with some useful methods for the