If you have use for a function that returns the actual decimal portion then you could split this up by removing the part that finds the decimal value itself and put it in a different function. Probably a better programming practice regardless.
I didn't do that here.
My use-case is displaying something per second.
After a while it becomes something / 1 and pretty much stays that way.
"Thing" and Seconds are always whole numbers.
So if it's 3 things every 5 seconds then I want it to display 0.60.
But if it's 3 things every second I want it to just display 3.
So what I'm trying to do is display a decimal value only if necessary and otherwise display a whole number.
The way it works is that you tell it to check if a decimal has value and the number of places you care about.
The code should be self-explanatory.
I didn't do that here.
My use-case is displaying something per second.
After a while it becomes something / 1 and pretty much stays that way.
"Thing" and Seconds are always whole numbers.
So if it's 3 things every 5 seconds then I want it to display 0.60.
But if it's 3 things every second I want it to just display 3.
So what I'm trying to do is display a decimal value only if necessary and otherwise display a whole number.
The way it works is that you tell it to check if a decimal has value and the number of places you care about.
The code should be self-explanatory.
Code:
Public Function HasDecimalValue(ByRef Value As Double, ByRef DecimalPlaces As Long) As Boolean
Dim nValue As Long
Dim rDecimal As Double
' Determines if Decimal = 0 to number of decimal places.
' HasDecimalValue 4.04, 2 returns True.
' HasDecimalValue 4.04, 1 returns False.
' HasDecimalValue 3.009, 3 Returns True.
' HasDecimalValue 3.009, 2 Returns False.
nValue = Int(Value)
If nValue = Value Then Exit Function
rDecimal = (Value - nValue) * (10 ^ DecimalPlaces) ' You would move rDecimal = (Value - nValue) to a separate function that returns the entire decimal portion of a number if you want that.
nValue = Int(rDecimal)
If nValue = 0 Then Exit Function
HasDecimalValue = True
End Function
' This next part is air code.
Function FormatNumber(ByRef Number As Double, ByRef DecimalPlaces As Long) As String
If HasDecimalValue(Number, DecimalPlaces) then
FormatNumber =Format$(Number,"0." & String$(DecimalPlaces, "0"))
Else
FormatNumber = Cstr$(Int(Number))
End if