Garren Fitzenreiter
Garren Fitzenreiter

Reputation: 839

Dividing doubles returns 0

Below I have the code in my project for a base 58 conversion i've written. Getting the remainder of two small numbers works fine, but when trying to get the remainder of two large numbers represented like for example - 1.03475761285374E+33 returns 0. Is there a way to divide doubles and get a remainder?

Function Base58Value(sInput As String) As String

'reverse the input
sInput = StrReverse(sInput)

'get the length of the input string
Dim inputLen As Long
inputLen = Len(sInput)

'set up an array for each character
Dim sCharacter() As Integer
ReDim sCharacter(inputLen)

'set up an array for step 2 - index times 8 to the 2nd power
Dim sStep2() As Double
ReDim sStep2(inputLen)

'set up an array or step 3
Dim sStep3() As Double
ReDim sStep3(inputLen)

Dim sFinalNumber As Double
For x = 1 To inputLen
curchar$ = Mid(sInput, x, 1)
sCharacter(x) = Asc(curchar)
sStep2(x) = 2 ^ ((x - 1) * 8)
sStep3(x) = sCharacter(x) * sStep2(x)
sFinalNumber = sFinalNumber + sStep3(x)
Next x

Dim sRemainder() As Integer
ReDim sRemainder(0)
Dim sValue As Double
sValue = sFinalNumber
Dim sNextValue As Double
Dim sIter As Long
sIter = 0

Do Until Fix(sValue) = 0
DoEvents
ReDim Preserve sRemainder(sIter + 1)
sRemainder(sIter) = sMod(Fix(sValue), 58)
sValue = Fix(sValue / 58)
sIter = sIter + 1
Loop

Dim ConversionTable$
ConversionTable = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
Dim addValues As String
addValues = ""
Dim xI As Integer
For xI = 0 To UBound(sRemainder) - 1
DoEvents
List1.AddItem (sRemainder(xI))
addValues = addValues + Mid(ConversionTable, sRemainder(xI) + 1, 1)
Next xI

Base58Value = StrReverse(addValues)

End Function

Public Function sMod(a, b)
Dim x As Variant
x = a / b
x = x - Fix(x)
x = x * b
sMod = x
End Function

Upvotes: 1

Views: 68

Answers (1)

Jim Mack
Jim Mack

Reputation: 1144

Without actually analyzing what your code does, I'll say that floating point values represent a compromise between range and precision: it's not possible to have all of both. A very large float is not necessarily able to store a very precise value.

There are only about 53 bits of actual precision in a VB double, so the largest integer that can be stored exactly is around 15 digits long.

Try using Decimals (variant) instead. I'm not sure they'll do what you need because as I said I didn't analyze your code. But they do offer extended precision -- up to 29 decimal digits, twice what a double offers.

Upvotes: 1

Related Questions