CodeMonkey
CodeMonkey

Reputation: 13

VB.Net String to double

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).

Upvotes: 1

Views: 5115

Answers (3)

Guffa
Guffa

Reputation: 700372

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)

Upvotes: 2

Ralf de Kleine
Ralf de Kleine

Reputation: 11734

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

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190941

Try Double.TryParse(...).

Upvotes: 0

Related Questions