I need to truncate the amount of decimal places of my double value for display in a textbox. How would one achieve this with vba?
So fun story. I was messing around with a quick VB conversion function. I just want to truncate a double into an integer.
value = Int(83.768)
value == 83
Awesome, something in VB actually worked.
Oops, I forgot it doesn't work with negative numbers
value = Int(-83.768)
value == -84
... yeah that just happened. VB uses Banker rounding.
Public Function Trunc(ByVal value As Double) As Integer
' Truncate by calling Int on the Absolute value then multiply by the sign of the value.
' Int cannot truncate doubles that are negative
Trunc = (Abs(value) / value) * Int(Abs(value))
End Function
If you want specific decimal places do what Makah did only with Abs around the value so Int can truncate properly.
Public Function Trunc2(ByVal value As Double, Optional ByVal num As Integer = 1) As Double
' Truncate by calling Int on the Absolute value then multiply by the sign of the value.
' Int cannot truncate doubles that are negative
Dim sign As Integer
sign = Abs(value) / value
Trunc2 = sign * (Int(Abs(value) * (10 ^ num)) / (10 ^ num))
End Function