Andy Charity - 1 month ago 5x

Vb.net Question

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`

`var`

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:

Source (Stackoverflow)

Comments