■85853 |
Re[1]: 指数表記された文字列の数値変換方法について |
□投稿者/ 魔界の仮面弁士 -(2017/11/29(Wed) 09:42:45)
| ■No85832 (たかじ さん) に返信 > 指数表記されている文字列(2.12345678975E9や3.4E+38など)を > decimalにTryParseすると、
Decimal ではなく decimal と表記されていることからして、 VB ではなく C# をお使いでしょうか。
> 変換に失敗します。
前者は、NumberStyles を受け取る TryParse のオーバーロードを使えば変換できますが、 後者はどうやっても不可能です。最大値(decimal.MaxValue)を大幅に超えていますから…。
3.4E+38 はおろか、3.4E+29 でも不可能です。(3.4E+28 なら変換できますけれども) System.Decimal の scale は 0〜28 の範囲しか指定できません。 https://msdn.microsoft.com/ja-jp/library/bb1c1a6x.aspx
なお System.Decimal は、有効桁数も含めて保持されるため、 string s1 = "2.12345678975E9"; と string s2 = "2.12345678975000E9"; は異なる変換結果になることにご注意ください。
string s1 = "2.12345678975E9"; string s2 = "2.12345678975000E9";
NumberStyles ns = NumberStyles.AllowExponent | NumberStyles.Float; IFormatProvider fmt = CultureInfo.InvariantCulture;
decimal d1, d2; Console.WriteLine(decimal.TryParse(s1, ns, fmt, out d1)); Console.WriteLine(decimal.TryParse(s2, ns, fmt, out d2)); Console.WriteLine(d1 == d2); // 値としては同じ Console.WriteLine(d1); // 有効桁数12桁で表示される Console.WriteLine(d2); // 有効桁数15桁で表示される |
|