Matteo NNZ
Matteo NNZ

Reputation: 12665

conversion from "String" to "Single" Type not working

I have data stored into a string format which is using the comma to separate decimals from integers. The variable "dataPoint" is actually an element of a DataTable object that has been used to retrieve data from a SQLite .db file:

dataPoint = MyDataTable.Rows(0)(0) ="0,1563"

When I try to make the conversion using the following line of code:

convertedDataPoint = Convert.ToSingle(Strings.Replace(dataPoint, ",", "."))

... I get the following value:

>>> 1563.0

rather than

>>> 0.1563

What's wrong here? How should I convert these data properly?

Upvotes: 0

Views: 2220

Answers (1)

Nico Schertler
Nico Schertler

Reputation: 32597

Convert.ToSingle() uses the current thread's culture information to parse the number. If you want an invariant approach, you can specify which format the string is in:

convertedDataPoint = Convert.ToSingle(dataPoint, CultureInfo.InvariantCulture)

or the italian one:

convertedDataPoint = Convert.ToSingle(dataPoint, new CultureInfo("it"))

But don't instantiate a new CultureInfo each time. Create it once and use it everywhere you need it.

Anyway, your database should store the number in a consistent way. Preferably as a number, not as a string. If it has to be a string, then use a consistent formatting that does not depend on the computer's language settings.

Upvotes: 3

Related Questions