views:

26

answers:

3

Why is it that when I convert a string with value "22.882" to double, using Dbl() it loses precision and is converted to 2288.2?

I have to use a double since I'm using the constructor of System.Web.UI.WebControls.Unit (see http://msdn.microsoft.com/en-us/library/ctewx7ch.aspx).

A: 

Try Double.TryParse(...).

Daniel A. White
+1  A: 
Dim input As String = "22.882"
If Double.TryParse(input, Globalization.NumberStyles.Float, New Globalization.CultureInfo("en-US"), result) Then
    Return result
Else
    Return 0D ' Or error
End If
rdkleine
Thanks! The Globalization.NumberStyles.Float argument seems to do the trick. A regular TryParse also resulted in an incorrect value of 22882.0.
CodeMonkey
+1  A: 

There is no apparent reason why it would change the value to 2288.2, but if it actually ends up as 22882.0 then you are just using a culture that doesn't use period as decimal separtor.

You just have to specify a culture that does use the period as decimal separator:

 Dim d As Double = Double.Parse(theString, CultureInfo.InvariantCulture)
Guffa