nexno
nexno

Reputation: 449

Convert Integer to Single

I am using the Graph Control made by a user named "Aeonhack" in my .NET application. When adding, let's say, a point with the size 9, it has to be a Single like 9.0F.

So I want a function that converts an Integer like 9 into a single like 9.0F.

The normal CType won't work, and I also tried:

Private Function IntToSingle(ByVal Number As Integer) As Single
    Return CType(Number & ".0F", Single)
End Function

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    GraphConnections.AddValue(IntToSingle(7))
End Sub

This gives me this error:

Conversion from string "7.0F" to type 'Single' is not valid.

How can I fix this?

Upvotes: 1

Views: 4848

Answers (3)

David Specht
David Specht

Reputation: 9044

I think the confusion is with 7.0F. That is not the same thing as the string "7.0F".

Per Microsoft

Appending the literal type character F to a literal forces it to the single data type.

You could simply use the F to force a double literal to be a single data type.

GraphConnections.AddValue(7.0F)

If, however, you receive an integer variable, then you would need to convert or cast it to a single as suggested by @MarcinJuraszek.

dim point As Integer = 7

GraphConnections.AddValue(Convert.ToSingle(point))

Upvotes: 1

rory.ap
rory.ap

Reputation: 35260

You can use this to convert to a single: CSng(9), though I think this only works in VB.NET.

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

Use Convert.ToSingle:

Convert.ToSingle(Number)

Or just CType, without weird string concatenation:

CType(Number, Single)

Upvotes: 7

Related Questions