[decimal] conversion has some unexpected behavior depending on culture settings

I ran into an issue where I had to convert a string value to decimal, to run a switch case on it. Once the systemlocale setting was set to en-US, there were no issues with the script, but when set to nl-NL (or any other country that uses a comma as seperator), it didn’t work as expected.

When you look at the world map and/or list of countries on Wikipedia, you’ll see that more countries use a comma as seperator than the ones that use a dot, but it seems that Microsoft only thought of their own default setting, but maybe neglected the rest?

I used this code:

(I used colors to make it more clear which part was a ‘normal’ conversion and which part was a changed conversion, as I found out that the ‘normal’ conversion didn’t work with a comma as decimal seperator)
This is the result from the above code

As you can see in the result screenshot, the switch case won’t even run with numbers higher than 10, once there is a comma as decimal seperator. Because a 84,1 gets converted to 841 etc.
Small numbers get converted to a higher number as well (0.6 get changed to 6, 5.4 get changed to 54 etc.), but in my case, since I needed to check for percentages, they couldn’t be higher than 100.

If you want to test this script for yourself, I’ve added this line to the top of the script: [Threading.Thread]::CurrentThread.CurrentCulture = "nl-NL"
so you’ll be able to test it with a country that uses a comma as a seperator. You can use any other country as listed in the above wikipedia article, that uses a comma as decimal seperator and it should give the same result as the script I shared here. If you already live in a country that uses a comma as seperator, you can comment out the CurrentCulture line in the script.

You can download my sample script here.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s