Joseph Mawer
Joseph Mawer

Reputation: 298

vb.net Unable to keep decimal places when converting string to single

I have been working on a vb.net project and have run into a problem. I have tried various implementations from Stackoverflow and MSDN but nothing is working. All I am trying to do is convert a string value to a single and keep the precision.

An example of the code would be something like this:

Dim Total As Single = 0 
Dim s as String = "427.00"
Total += Single.Parse(s)

// Total = 427

// Expected : 427.00 <-- I need this

I have tried using cultureinfo.invariant, I have tried using string.format, I have tried using double instead of single,

I don't know what I am missing. Any insight would be appreciated, and I can provide more code of what the application is trying to do if necessary.

Upvotes: 1

Views: 1256

Answers (1)

interesting-name-here
interesting-name-here

Reputation: 1890

In addition to @Alex B.'s comment, this is how you would achieve this. Total is a String but the program will bomb if either is not a Single type giving you some type safety.

Dim Total As String = "0"
Dim s as String = "427.00"
Total = (Single.Parse(Total) + Single.Parse(s)).ToString("0.00")

Upvotes: 1

Related Questions