Android Code Snippet RandomNumber() - The most powerful number generator (B4A/B4J/B4i)

Let's say you need to gen
Here's a more powerful alternative to the usual Rnd() function. :)

Features:
Do you need to generate a negative number? Done.
Do you need it to have decimal places? Done.
Do you need to have zero excluded? Done.
B4X:
'Returns a random double between Lowest (inclusive) and Highest (exclusive), with n decimal places.
Sub RandomNumber(Lowest As Double, Highest As Double, DecimalPlaces As Int, PreventZero As Boolean) As Double
    Lowest  = Round(Lowest)
    Highest = Round(Highest)
    Dim Decimal As Double
    If DecimalPlaces > 0 Then Decimal = (Rnd(0, Power(10, DecimalPlaces))) / Power(10, DecimalPlaces)
    If Lowest = Highest Then
        Return Lowest
    Else
        If Lowest > Highest Then
            Dim TempValue = Lowest As Double
            Lowest   = Highest
            Highest  = TempValue
        End If
        Dim ReturnValue = Lowest + Rnd(0, Highest - Lowest) + Decimal As Double
        If ReturnValue = 0 And PreventZero Then
            Return RandomNumber(Lowest, Highest, DecimalPlaces, PreventZero)
        Else
            Return ReturnValue
        End If
    End If
End Sub

Usage:
B4X:
For i = 1 to 10
    Log(RandomNumber(-73, 65, 2, False))
Next

'Output:
'Program started.
'-33.63
'53.76
'17.16
'8.49
'1.21
'14.61
'-23.46
'53.79
'31.04
'-29.72
'54.42

Enjoy! :)
 
Last edited:
Top