To extract the decimal part of a number in B4A, you can use some basic mathematical operations and string manipulations. Here’s how you can achieve it:
Convert the number to a string.
Find the position of the decimal point.
Extract the substring starting from the position of the decimal point + 1.
Convert this substring back to a number if needed.
Here is the code that demonstrates this approach:
B4X:
Dim latitude As Double = 43.123456
Dim m As Long
' Convert the number to a string
Dim latitudeString As String = latitude
' Find the position of the decimal point
Dim decimalPosition As Int = latitudeString.IndexOf(".")
' Extract the decimal part as a substring
Dim decimalPart As String = latitudeString.SubString(decimalPosition + 1)
' Convert the decimal part to a long number
m = decimalPart
Log("Decimal part: " & m)
Dim num As Double = 43
If num.As(String).Contains(".") Then
Dim dec As Int = num.As(String).SubString((" " & num).IndexOf("."))
Else
Dim dec As Int = 0
End If
Log(dec)
IndexOf(".") is not suitable, because you could have a different symbol as decimal separator (possibly you would have to use a variable in which to put the system separator).
The following code should work:
B4X:
Dim Num As Double = 2.36
' Dim Num As Double = -2.36 ' to test negative numbers
Dim IntPart As Int
Dim DecimalPart As Double
If Num >= 0 Then
IntPart = Floor(Num)
Else
IntPart = Ceil(Num)
End If
DecimalPart = Abs(Num - IntPart)
DecimalPart = Round2(DecimalPart, 2)
Log("Original number: " & Num)
Log("Int part: " & IntPart)
Log("decimal part: " & DecimalPart)
Just for fun this works with no "." and negative numbers
B4X:
Dim num As Double = -43.123456
Dim dec As Int = IIf((""&num).indexof(".")=-1,0,num.As(String).SubString((" " & num).IndexOf("."))*IIf(num<0,-1,1))
Log(dec)
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.