Andy Charity Andy Charity - 2 months ago 11
Vb.net Question

Custom Data type - how to add implicit conversions and math operator capability

My code uses almost exclusively 8 decimal place variables. Because of the rounding issues with Double variable type I have to use x=Math.Round(x,8) after every calculation to get correct results.

I could use a class for a variable type to support only 8 decimal places, however I have to refer to all instances using the .var class property which is untidy.

Is there a better way to implement this ?

Public Class Double8
Private localval As Double
Public Sub New()
localval = 0
End Sub
Property var As Double
Get
Return localval
End Get
Set(value As Double)
localval = Math.Round(value, 8)
End Set
End Property
End Class

'Test rounding from below, at and above .....5
Dim n As New Double8
n.var = 0.123456789
MsgBox("0.123456789 stored as " & n.var.ToString)
n.var = 0.123456782
MsgBox("0.123456782 stored as " & n.var.ToString)
n.var = 0.123456785
MsgBox("0.123456785 stored as " & n.var.ToString)


What I want to do is use the type
Double8
in the same manner as one would the intrinsic data types in terms of assignment with implicit conversion and perform basic math operations (add, subtract, divide, multiply) with the type with out having to refer to the type's
var
property.

Answer

You can define both conversion operators and mathematical operators for you Double8 type. I have converted your Double8 to a structure because it makes more sense for something that represents a special case of Double. I have only implemented conversion to/from Double and addition/subtraction with Double. The other operators are up to you to implement.

Public Structure Double8
    Private localval As Double

    Property var As Double
        Get
            Return localval
        End Get
        Set(value As Double)
            localval = Math.Round(value, 8)
        End Set
    End Property

    Public Shared Widening Operator CType(d As Double) As Double8
        Return New Double8 With {.var = d}
    End Operator

    Public Shared Widening Operator CType(d8 As Double8) As Double
        Return d8.var
    End Operator

    Public Shared Operator +(d8 As Double8, d As Double) As Double
        Return d8.var + d
    End Operator

    Public Shared Operator -(d8 As Double8, d As Double) As Double
        Return d8.var - d
    End Operator
End Structure

The conversion operators (CType) will allow assignment between types. Dim d8 As Double8 = 1.123456789#

The others operators (math and logical) will allow your types use in equations.

Dim d1 As Double = 5.0 + d8
Dim d2 As Double8 = d8 - 5.0

see:

How to: Define a Conversion Operator (Visual Basic)

How to: Define an Operator (Visual Basic)