Wine Too Wine Too - 1 year ago 119 Question

Convert numeric data from database

In my system default decimal separator is comma.

In database I have written numeric values as strings but in format with decimal separator point.

Now, when I read data from database like this "3.2" with following code I get value 32D!

NumericUpDown1.Value = CDec(reader("myfield"))

Is here any way that I can get decimal value of 3,2 from showed code in described situation?

Answer Source

You know your number is stored as a string in the format "1,23456". You are dealing with a globalization issue, and as such, you could convert the string using the appropriate culture formatting settings.

NumericUpDown.Value is of type Decimal, so I use the function Convert.ToDecimal.

For this example, I'll assume the number being inserted was stored in the database by a Croatian, so I'd use "hr-HR" for the culture name.

Dim myFieldCroatia As String = "1,2345678901234567890123456789"
NumericUpDown1.Value = Convert.ToDecimal(myFieldCroatia, New Globalization.CultureInfo("hr-HR"))

And if it were stored by an American, I'd use "en-US"

Dim myFieldUnitedStates As String = "1.2345678901234567890123456789"
NumericUpDown2.Value = Convert.ToDecimal(myFieldUnitedStates, New Globalization.CultureInfo("en-US"))

As an aside, if you had first converted to Double, and implicitly converted to Decimal, you would have lost any precision past 15 to 17 decimal places. Not sure if it's required, but it's worthy of noting.

See MSDN for a complete list of culture names

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download