开发者

Convert String to Decimal Mystery

开发者 https://www.devze.com 2023-03-16 05:13 出处:网络
I\'m facing a problem about the conversion from string to decimal using C# .NET. The problem is tha开发者_运维百科t I have wrote the following code and works fine on my development Windows 7 .NET Fram

I'm facing a problem about the conversion from string to decimal using C# .NET. The problem is tha开发者_运维百科t 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


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);


You are affected by regional settings. When the string 85.00 is parsed in a locale where full stop is used as decimal separator the result is 85.00. If comma is used as decimal separator the result is 8500.

Use the overload where you specify a CultureInfo:

var dec = Convert.ToDecimal(strDec, CultureInfo.GetCultureInfo("en"));

You can also use CultureInfo.InvariantCulture which is the default .NET CultureInfo and similar to the English CultureInfo.

In a production quality application you should always specify or know the CultureInfo used when you parse and format strings. If you turn code analysis on in your project you will get warnings when you forget to do that: CA1304: Specify CultureInfo.


Try using culture-ignorant mode

var decimalValue = Convert.ToDecimal(stringValue, CultureInfo.InvariantCulture);


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"));


so, i used next function

public static Decimal GetInvariantDecimal(string Value)
{
    try
    {
        Decimal d = 0;
        if (Decimal.TryParse(Value, out d))
            return d;
        else
            return Convert.ToDecimal(Value, System.Globalization.CultureInfo.InvariantCulture);
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

But it only for Russian like decimal separator

0

精彩评论

暂无评论...
验证码 换一张
取 消