Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

2 decimal places 1

Status
Not open for further replies.

buddyel

MIS
Mar 3, 2002
279
US

I am trying to store a variable, and want it to be stored as a two decimal number. This is what i have....

Dim LO as Single = Format(LO, "Fixed")

It shows 4 decimal places with or without the Format(..). I tried doing this....

Dim LO as Single = Format(LO, "#####.##")

I get a message saying "Cast from String "" to type 'Single' is not valid..

It is probably really stupid I am doing, but if anyone can help, I would appreciate it. Thanks
 
Hello buddyel,
The error that you are getting is quite common because it tries to convert a string (the format function returns a string) to a single. You can use that IF you want to display the data (also you can use LO.ToString("####.##") )

If you want to store the number in the single then you need to use the round function. Try the following:

----------- Cut here --------------------

Dim LO As Single
LO = 1.324234234242 'Set the value of the variable
Debug.WriteLine(LO.ToString("####.##")) 'Display the value formatted with two decimal places
LO = Math.Round(LO, 2) 'Do the actual rounding
Debug.WriteLine(LO) 'Display the result

----------- Cut here --------------------

The difference between the line 3 of the code and the line 5 is that the value of LO in line 3 remains 1.324234234242 but in line 5 the value stored in the LO becomes 1.32

Hope that this helps,
Camel
 

I achieve the proper amount of decimal places with this code...
LO = Math.Round(LO, 2)
but it doesnt appear to actually round the number. I have a number coming out as 31.25 when it should be 31.26. Any ideas?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top