dav*_*vid 17 .net c# type-conversion
字符串值是"90-".为什么小数会将其解析为"-90"但却double抛出FormatException?
var inputValue= "90-";
Console.WriteLine(decimal.Parse(inputValue));
Console.WriteLine(double.Parse(inputValue));
Run Code Online (Sandbox Code Playgroud)
J..*_*... 15
的decimal.Parse(string s)过载,在默认情况下,被称为与NumberStyle NumberStyles.Number其被定义为:
指示使用AllowLeadingWhite,AllowTrailingWhite,AllowLeadingSign,AllowTrailingSign,AllowDecimalPoint和AllowThousands样式.这是一种复合数字样式.
请注意,AllowTrailingSign包括在内.如果您希望自定义行为,那么您应该显式调用重载,以允许您指定数字样式并根据您的需要进行定制.
两者之间的实施是不同的:
public static double Parse(String s) {
return Parse(s, NumberStyles.Float| NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo);
}
public static Decimal Parse(String s) {
return Number.ParseDecimal(s, NumberStyles.Number, NumberFormatInfo.CurrentInfo);
}
Run Code Online (Sandbox Code Playgroud)
哪里
NumberStyles.Float = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign |
AllowDecimalPoint | AllowExponent,
NumberStyles.Number = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign |
AllowDecimalPoint | AllowThousands
Run Code Online (Sandbox Code Playgroud)
因此decimal.Parse允许尾随标志,但double.Parse不允许.
看起来MSDN上的文档不准确:
参数s包含以下形式的数量:
[WS] [符号] [数字,]数字[.fractional位数] [WS]
它应该表明尾随符号也是有效的.
| 归档时间: |
|
| 查看次数: |
891 次 |
| 最近记录: |