decimal.TryParse() drops leading “1”

后端 未结 2 850
刺人心
刺人心 2021-02-05 12:35

Short and sweet version:

On one machine out of around a hundred test machines decimal.TryParse() is converting \"1.01\" to 0.01


Okay, this is going to soun

相关标签:
2条回答
  • 2021-02-05 12:49

    I am able to reproduce your results. Consider:

    public NumberFormatInfo OneIsPositiveSignFormat()
    {
        NumberFormatInfo custom = new NumberFormatInfo();
        custom.PositiveSign = "1";
        return custom;
    }
    

    And then:

    if (decimal.TryParse(value, NumberStyles.Number, OneIsPositiveSignFormat(), out val))
    

    The thing is: Regional Settings does not show you the current positive sign, and mainly: you did not set the culture when parsing the number.

    The value may come from various locations: It may have come from the registry as the system defaults, or the defaults could have been set by code:

    CultureInfo customCulture = (CultureInfo)CultureInfo.InvariantCulture.Clone();
    customCulture.NumberFormat = OneIsPositiveSignFormat();
    Thread.CurrentThread.CurrentCulture = customCulture;
    
    0 讨论(0)
  • 2021-02-05 12:58

    see how the regional settings are set for this computer it might be that "." is set as thousand separator not as decimal separator. Try using Decimal.TryParse (String, NumberStyles, IFormatProvider, out Decimal val) and pass NumberFormatInfo created with decimal separator "."

    0 讨论(0)
提交回复
热议问题