Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to Decimal Mystery

I'm facing a problem about the conversion from string to decimal using C# .NET. The problem is that I have wrote the following code and works fine on my development Windows 7 .NET Framework 3.5 system. But, if I move the application on the Windows 2003 Server .NET 3.5 Framework the result is different. Can anyone understand what happen there?

Code:

dec = Convert.ToDecimal(strDec);

Windows 7 result: 85.00 Windows 2003 result: 8500

like image 580
user730153 Avatar asked Jun 27 '11 21:06

user730153


People also ask

How do you convert strings to decimals?

Converting a string to a decimal value or decimal equivalent can be done using the Decimal. TryParse() method. It converts the string representation of a number to its decimal equivalent.

How do I convert a string to a decimal in Python?

literal_eval() function to convert the hexadecimal string to decimal string. convertion = literal_eval(testing_string) # At last, print result. print ("The converted hexadecimal string into decimal string is: " + str(convertion))

What is decimal parse in C#?

Parse() is a C# method that is used to convert the string representation of a number to its decimal equivalent.


2 Answers

We faced with the issue when

Convert.ToDecimal("0.5", CultureInfo.InvariantCulture); 

was 0,5

, but

Convert.ToDecimal("0,5", CultureInfo.InvariantCulture);

was 5!

The solution was to use

Convert.ToDecimal(stringValue.Replace(",", "."), CultureInfo.GetCultureInfo("en"));
like image 100
nZeus Avatar answered Oct 04 '22 14:10

nZeus


It may be that the region and culture settings on your server are set with , as decimal, and . as digit grouping. See Control Panel/region and culture settings.

If this numeric string is generated by your application, I would use CultureInfo.InvariantCulture in both places.

     Decimal dec = 85.0m;
     string s = dec.ToString (CultureInfo.InvariantCulture);
     decimal.Parse(s, CultureInfo.InvariantCulture);
like image 42
agent-j Avatar answered Oct 04 '22 14:10

agent-j