Search code examples
excelvbatype-conversion

Unexpected cell content after type conversion


I have a simple Sub procedure which gives the expected value of 0.32 in the Immediate window but gives a "strange" number in a Worksheet cell (A1: 0.319999992847443). Any idea why this happens? How to prevent it?

Sub Test()
Dim arr(1 To 1) As Variant
Dim str   As String
str = "+0.32"
arr(1) = Round(CSng(str), 2)  ' convert to Single and round to avoid a "strange" number
Debug.Print arr(1)            ' 0.32 as expected
Cells(1, 1) = arr(1)          ' 0.319999992847443, "strange" number
End Sub

Solution

  • Just put it into Excel and the following gives 0.32:

    Sub Test()
      Dim arr(1 To 1) As Variant
      Dim str   As String
    
      str = "+0.32"
      arr(1) = Round(CDbl(str), 2)  ' convert to Single and round to avoid a "strange" number
      Debug.Print arr(1)            ' 0.32 as expected
      Cells(1, 1) = arr(1)          ' 0.319999992847443, "strange" number
    End Sub
    

    *Edit - I done this whilst the people above commented. It's the CSng, needs to be CDbl as commented.