ASP.NET MVC binding decimal value

后端 未结 4 2105
既然无缘
既然无缘 2021-01-04 00:19

I\'m trying to figure out why framework refuses to bind \"1,234.00\" value to decimal. What can be the reason for it?

Values like \"123.00\" or \"123.0000\" bind suc

4条回答
  •  温柔的废话
    2021-01-04 01:10

    The issue here appears to be the default Number Styles applied to Decimal.Parse(string).

    From MSDN documentation

    The remaining individual field flags define style elements that may be, but do not have to be, present in the string representation of a decimal number for the parse operation to succeed.

    So this means that both d1 and d2 below successfully parse

                    var d1 = Decimal.Parse("1,232.000");
    
                    var d2 = Decimal.Parse("1,232.000", NumberStyles.Any);
    

    However when applying the type convertor it appears that this essentially only allows the allow training spaces, allow decimal point and allow leading sign. As such the d3 express below will throw a runtime error

                    var d3 = Decimal.Parse("1,232.000", NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | 
                                            NumberStyles.AllowTrailingWhite | NumberStyles.AllowDecimalPoint);
    

提交回复
热议问题