Convert String to Decimal Mystery

别说谁变了你拦得住时间么 提交于 2020-01-02 01:47:26

问题


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


回答1:


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



回答2:


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.




回答3:


Try using culture-ignorant mode

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



回答4:


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



回答5:


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



来源:https://stackoverflow.com/questions/6499003/convert-string-to-decimal-mystery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!