Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Determine order of magnitude... 3

Status
Not open for further replies.

sunaj

Technical User
Feb 13, 2001
1,474
0
0
DK
Hi,

Can anyone think of a smart way to determine the odrer of magnintude of a number.

3459 is of the order 1000
3 is of the order 1
0.0056 is of the order 0.001

len(cstr(int(TheNumber))) works for numbers larger than 1, but not for numbers between 0 and 1.

Sunaj
 
10 ^ CLng(Right(Format(0.0056, "0.00E+00"), 3))
 
Sunaj,

If you want negative numbers to have a negative order of magnitude, use this code:

Public Function OrderOfMagnitude(x As Double) As Double

If x = 0 Then
OrderOfMagnitude = 0
ElseIf x < 0 Then
OrderOfMagnitude = -10 ^ Int(Log(-x) / Log(10))
Else
OrderOfMagnitude = 10 ^ Int(Log(x) / Log(10))
End If

End Function

If you don't (i.e. the order of magnitude is always >= 0) then use this form:

Public Function OrderOfMagnitude(x As Double) As Double

If x = 0 Then
OrderOfMagnitude = 0
Else
OrderOfMagnitude = 10 ^ Int(Log(Abs(x)) / Log(10))
End If

End Function
 
Of course ScottGS, the logarithm, why did I not think of that?

Suanj
 
I think strongm's solution is a tad more elegant though...

Scott
 
Hmmmmmmmmmm, Verrrrrrrrrrry interrrrrrresting ...

Some Good points in BOTH soloutions, why not combine them?

Code:
Public Function basOrMag(ValIn As Variant) As Single

    Dim SignIn As Integer
    Dim MyVal As Double
    Dim tmpOrMag As Double

    If (ValIn < 0) Then
        SignIn = -1
     Else
        SignIn = 1
    End If
    MyVal = Abs(ValIn)

    tmpOrMag = 10 ^ Int(Log(MyVal) / Log(10))
    If (tmpOrMag > 1) Then
        basOrMag = CSng(Len(Trim(str(tmpOrMag))))
     Else
        basOrMag = tmpOrMag
        'Len(right(str(tmpOrMag), Len(str(tmpOrMag)) - InStr(tmpOrMag, &quot;.&quot;)))
    End If
    basOrMag = basOrMag * SignIn

End Function
MichaelRed
mred@att.net

There is never time to do it right but there is always time to do it over
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top