PaulWill
PaulWill

Reputation: 623

Using an specific format string for numbers

I have some numbers in this format that I would like to change

121.23
12312
1.123
1234.5

how can I force them to use a format of 12.123 so it has a dot always after the second number.

Upvotes: 0

Views: 71

Answers (1)

rory.ap
rory.ap

Reputation: 35270

This is not a string format operation. You need to multiply or divide the number by 10 until it's less than 100 or greater than or equal to 10. Eg:

Function Transform(ByVal toTransform As Decimal) As Decimal
    Transform = toTransform

    If (Transform >= 100) Then
        Do While Transform >= 100
            Transform /= 10
        Loop
    ElseIf (Transform < 10) Then
        Do While Transform < 10
            Transform *= 10
        Loop
    End If
End If

Or here's a version that is more generic so you can use it to get any number of decimal places:

Function Transform(ByVal toTransform As Decimal, ByVal numberOfPlaces As Integer) As Decimal
    Transform = toTransform
    Dim min = 10 ^ (numberOfPlaces - 1)
    Dim max = 10 ^ numberOfPlaces

    If (Transform >= max) Then
        Do While Transform >= max
            Transform /= 10
        Loop
    ElseIf (Transform < min) Then
        Do While Transform < min
            Transform *= 10
        Loop
    End If
End Function

Basically, it multiplies or divides the number by 10 which moves the decimal point in the required direction. It does so until the result is less than or equal to the maximum value in that range and greater than or equal to the minimum value in that range.

Upvotes: 1

Related Questions