带后缀的字符串解析失败

String with suffix fails parsing

每当将带有后缀的字符串传递给 decimal 时,解析都会失败。

decimal testValue;
decimal.TryParse("5M", NumberStyles.Number, CultureInfo.CurrentCulture, out testValue)

以下解析将 return false.

为什么传入带后缀的字符串时TryParse会失败?

因为 没有办法 在不删除 M 部分的情况下解析您的字符串。而NumberStyles的none有这样的功能。

可以 建议 Replace 你的 M 使用空字符串,但这只能解决你的情况,它不会是一般的解决方案。

decimal testValue;
decimal.TryParse("5M".Replace("M", ""), NumberStyles.Number, 
                                        CultureInfo.CurrentCulture, out testValue);

A real-type-suffix 指定数字类型。它告诉 C# 编译器什么是数字文字类型。在字符串中,它表示 nothing。这只是另一个角色。

因为Decimal.TryParse does not support it.

Depending on the value of style, the s parameter may include the following elements:

[ws][$][sign][digits,]digits[.fractional-digits][e[sign]digits][ws]

Elements in square brackets ([ and ]) are optional. The following table describes each element.

ws: Optional white space. White space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag. It can appear at the end of s if style includes the NumberStyles.AllowTrailingWhite flag.

$: A culture-specific currency symbol. Its position in the string is defined by the NumberFormatInfo.CurrencyNegativePattern or NumberFormatInfo.CurrencyPositivePattern properties of the NumberFormatInfo object returned by the IFormatProvider.GetFormat method of the provider parameter. The currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag.

sign: An optional sign.

digits: A sequence of digits ranging from 0 to 9.

.: A culture-specific decimal point symbol.

fractional-digits: A sequence of digits ranging from 0 to 9.