egolive
egolive

Reputation: 397

Decimal keep decimalplaces

I might have a easy question.

I'm trying to convert a string into an decimal.

My String looks like this: 95,34

After i convert it into a decimal its 9534D

It lost his decimal places.

Why? And how can i keep them?

            Dim decbla As String = hfBauvorhaben_Beleihungsauslauf.Value
            eBeleihungsauslauf = Convert.ToDecimal(decbla)

I write it into an Database and later i need it back with decimal places.

Upvotes: 1

Views: 254

Answers (2)

Max
Max

Reputation: 13338

This has probably something to do with culture, could you try using InvariantCulture?

Change:

eBeleihungsauslauf = Convert.ToDecimal(decbla)

For:

eBeleihungsauslauf = Convert.ToDecimal(decbla, CultureInfo.InvariantCulture)

Or:

eBeleihungsauslauf = Decimal.Parse(decbla, CultureInfo.InvariantCulture)

In addition, for testing if the string can be converted to a valid decimal, you could use: Decimal.TryParse

Upvotes: 1

Markus
Markus

Reputation: 22456

When reading a decimal number from a string, cultural or regional characteristics are important as different regions use different decimals or thousands separators. So in your case, the comma is not interpreted as a decimal separator and therefore is not respected.

The current culture is set on the thread in the Thread.CurrentCulture property. This property is initialized at the beginning of the request (for a web application) or when you start the application. You might want to check the value in the debugger to find out which setting is used.

If you do not specify a specific culture when parsing the string, the setting of the thread is used.

Based on the names of your variables and how the string is formatted I assume that you need to use german region settings for parsing the string. Also, you can use Decimal.Parse to be able to specify a FormatProvider (you can also specify the FormatProvider for Convert.ToDecimal):

Dim cult As New System.Globalization.Culture("de-DE")
Dim decbla As String = hfBauvorhaben_Beleihungsauslauf.Value
eBeleihungsauslauf = Decimal.Parse(decbla, cult)

If you want to handle parsing problems due to the format without an exception, also have a look at the Decimal.TryParse method that returns a Boolean that signals whether parsing was successful or not.

Instead of having to specify the culture each time you need to parse a value, you might want to check whether you can set your application to use the right culture settings. It depends on the type of your application (Windows, Web) how you can do this in detail. It usually involves setting Thread.CurrentCulture (and most likely CurrentUICulture) at some point in time to the desired setting.

Upvotes: 1

Related Questions