decimal.TryParse() drops leading “1”

后端 未结 2 849
刺人心
刺人心 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;
    

提交回复
热议问题