Double.Parse メソッド

定義

数値の文字列形式を、等価の倍精度浮動小数点数に変換します。

オーバーロード

Parse(String, NumberStyles, IFormatProvider)

指定したスタイルおよびカルチャ固有の書式での数値の文字列形式を、等価の倍精度浮動小数点数に変換します。

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

指定したスタイルおよびカルチャ固有の書式による数値の文字列表現を含む文字スパンを、等価の倍精度浮動小数点数に変換します。

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

UTF-8 文字のスパンを値に解析します。

Parse(String, IFormatProvider)

指定したカルチャに固有の書式による数値の文字列形式を、それと等価な倍精度浮動小数点数に変換します。

Parse(String)

数値の文字列形式を、等価の倍精度浮動小数点数に変換します。

Parse(ReadOnlySpan<Char>, IFormatProvider)

文字のスパンを値に解析します。

Parse(ReadOnlySpan<Byte>, IFormatProvider)

UTF-8 文字のスパンを値に解析します。

Parse(String, NumberStyles)

数値の指定したスタイルでの文字列形式を、それと等価な倍精度浮動小数点数に変換します。

注釈

.NET Core 3.0 以降では、表すには大きすぎる値は、IEEE 754 仕様で必要に応じて または NegativeInfinityPositiveInfinity丸められます。 .NET Frameworkを含む以前のバージョンでは、大きすぎる値を解析するとエラーが発生しました。

Parse(String, NumberStyles, IFormatProvider)

指定したスタイルおよびカルチャ固有の書式での数値の文字列形式を、等価の倍精度浮動小数点数に変換します。

public:
 static double Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider);
public:
 static double Parse(System::String ^ s, System::Globalization::NumberStyles style, IFormatProvider ^ provider) = System::Numerics::INumberBase<double>::Parse;
public static double Parse (string s, System.Globalization.NumberStyles style, IFormatProvider provider);
public static double Parse (string s, System.Globalization.NumberStyles style, IFormatProvider? provider);
static member Parse : string * System.Globalization.NumberStyles * IFormatProvider -> double
Public Shared Function Parse (s As String, style As NumberStyles, provider As IFormatProvider) As Double

パラメーター

s
String

変換する数値を含んだ文字列。

style
NumberStyles

s で使用可能なスタイル要素を示す、列挙値のビットごとの組み合わせ。 通常指定する値は、AllowThousands と組み合わせた Float です。

provider
IFormatProvider

s に関するカルチャ固有の書式情報を提供するオブジェクト。

戻り値

s で指定した数値または記号と等価の倍精度浮動小数点数。

実装

例外

snullです。

s が数値を表していません。

styleNumberStyles 値ではありません。

または

styleAllowHexSpecifier 値です。

.NET Framework および .NET Core 2.2 以前のバージョンのみ: sDouble.MinValue より小さいか、Double.MaxValue より大きい数値を表します。

次の例は、 メソッドを使用 Parse(String, NumberStyles, IFormatProvider) して、温度値のいくつかの文字列表現をオブジェクトに割り当てる方法を Temperature 示しています。

using System;
using System.Globalization;

public class Temperature
{
   // Parses the temperature from a string. Temperature scale is
   // indicated by 'F (for Fahrenheit) or 'C (for Celsius) at the end
   // of the string.
   public static Temperature Parse(string s, NumberStyles styles,
                                   IFormatProvider provider)
   {
      Temperature temp = new Temperature();

      if (s.TrimEnd(null).EndsWith("'F"))
      {
         temp.Value = Double.Parse(s.Remove(s.LastIndexOf((char)39), 2),
                                   styles, provider);
      }
      else
      {
         if (s.TrimEnd(null).EndsWith("'C"))
            temp.Celsius = Double.Parse(s.Remove(s.LastIndexOf((char)39), 2),
                                        styles, provider);
         else
            temp.Value = Double.Parse(s, styles, provider);
      }
      return temp;
   }

   // Declare private constructor so Temperature so only Parse method can
   // create a new instance
   private Temperature()   {}

   protected double m_value;

   public double Value
   {
      get { return m_value; }
      private set { m_value = value; }
   }

   public double Celsius
   {
      get { return (m_value - 32) / 1.8; }
      private set { m_value = value * 1.8 + 32; }
   }

   public double Fahrenheit
   {
      get {return m_value; }
   }
}

public class TestTemperature
{
   public static void Main()
   {
      string value;
      NumberStyles styles;
      IFormatProvider provider;
      Temperature temp;

      value = "25,3'C";
      styles = NumberStyles.Float;
      provider = CultureInfo.CreateSpecificCulture("fr-FR");
      temp = Temperature.Parse(value, styles, provider);
      Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.",
                        temp.Fahrenheit, temp.Celsius);

      value = " (40) 'C";
      styles = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite
               | NumberStyles.AllowParentheses;
      provider = NumberFormatInfo.InvariantInfo;
      temp = Temperature.Parse(value, styles, provider);
      Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.",
                        temp.Fahrenheit, temp.Celsius);

      value = "5,778E03'C";      // Approximate surface temperature of the Sun
      styles = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands |
               NumberStyles.AllowExponent;
      provider = CultureInfo.CreateSpecificCulture("en-GB");
      temp = Temperature.Parse(value, styles, provider);
      Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.",
                        temp.Fahrenheit.ToString("N"), temp.Celsius.ToString("N"));
   }
}
open System
open System.Globalization

// Declare private constructor so Temperature so only Parse method can create a new instance
type Temperature private () =

    let mutable m_value = 0.

    member _.Value
        with get () = m_value
        and private set (value) = m_value <- value

    member _.Celsius
        with get() = (m_value - 32.) / 1.8
        and private set (value) = m_value <- value * 1.8 + 32.

    member _.Fahrenheit =
        m_value

    // Parses the temperature from a string. Temperature scale is
    // indicated by 'F (for Fahrenheit) or 'C (for Celsius) at the end
    // of the string.
    static member Parse(s: string, styles: NumberStyles, provider: IFormatProvider) =
        let temp = new Temperature()

        if s.TrimEnd(null).EndsWith "'F" then
            temp.Value <- Double.Parse(s.Remove(s.LastIndexOf(char 39), 2), styles, provider)
        else
            if s.TrimEnd(null).EndsWith "'C" then
                temp.Celsius <- Double.Parse(s.Remove(s.LastIndexOf(char 39), 2), styles, provider)
            else
                temp.Value <- Double.Parse(s, styles, provider)
        temp

[<EntryPoint>]
let main _ =
    let value = "25,3'C"
    let styles = NumberStyles.Float
    let provider = CultureInfo.CreateSpecificCulture "fr-FR"
    let temp = Temperature.Parse(value, styles, provider)
    printfn $"{temp.Fahrenheit} degrees Fahrenheit equals {temp.Celsius} degrees Celsius."

    let value = " (40) 'C"
    let styles = NumberStyles.AllowLeadingWhite ||| NumberStyles.AllowTrailingWhite ||| NumberStyles.AllowParentheses
    let provider = NumberFormatInfo.InvariantInfo
    let temp = Temperature.Parse(value, styles, provider)
    printfn $"{temp.Fahrenheit} degrees Fahrenheit equals {temp.Celsius} degrees Celsius."

    let value = "5,778E03'C"      // Approximate surface temperature of the Sun
    let styles = NumberStyles.AllowDecimalPoint ||| NumberStyles.AllowThousands ||| NumberStyles.AllowExponent
    let provider = CultureInfo.CreateSpecificCulture "en-GB"
    let temp = Temperature.Parse(value, styles, provider)
    printfn $"{temp.Fahrenheit:N} degrees Fahrenheit equals {temp.Celsius:N} degrees Celsius."

    0
Imports System.Globalization

Public Class Temperature
   ' Parses the temperature from a string. Temperature scale is 
   ' indicated by 'F (for Fahrenheit) or 'C (for Celsius) at the end
   ' of the string.
   Public Shared Function Parse(s As String, styles As NumberStyles, _
                                provider As IFormatProvider) As Temperature
      Dim temp As New Temperature()
      
      If s.TrimEnd(Nothing).EndsWith("'F") Then
         temp.Value = Double.Parse(s.Remove(s.LastIndexOf("'"c), 2), _
                                   styles, provider)
      Else
         If s.TrimEnd(Nothing).EndsWith("'C") Then
            temp.Celsius = Double.Parse(s.Remove(s.LastIndexOf("'"c), 2), _
                                        styles, provider)
         Else
            temp.Value = Double.Parse(s, styles, provider)         
         End If
      End If
      Return temp      
   End Function 
   
   ' Declare private constructor so Temperature so only Parse method can
   ' create a new instance
   Private Sub New 
   End Sub

   Protected m_value As Double
   
   Public Property Value() As Double
      Get
         Return m_value
      End Get
      
      Private Set
         m_value = Value
      End Set
   End Property
   
   Public Property Celsius() As Double
      Get
         Return (m_value - 32) / 1.8
      End Get
      Private Set
         m_value = Value * 1.8 + 32
      End Set
   End Property
   
   Public ReadOnly Property Fahrenheit() As Double
      Get
         Return m_Value
      End Get   
   End Property   
End Class

Public Module TestTemperature
   Public Sub Main
      Dim value As String
      Dim styles As NumberStyles
      Dim provider As IFormatProvider
      Dim temp As Temperature
      
      value = "25,3'C"
      styles = NumberStyles.Float
      provider = CultureInfo.CreateSpecificCulture("fr-FR")
      temp = Temperature.Parse(value, styles, provider)
      Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.", _
                        temp.Fahrenheit, temp.Celsius)
      
      value = " (40) 'C"
      styles = NumberStyles.AllowLeadingWhite Or NumberStyles.AllowTrailingWhite _
               Or NumberStyles.AllowParentheses
      provider = NumberFormatInfo.InvariantInfo
      temp = Temperature.Parse(value, styles, provider)
      Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.", _
                        temp.Fahrenheit, temp.Celsius)
      
      value = "5,778E03'C"      ' Approximate surface temperature of the Sun
      styles = NumberStyles.AllowDecimalPoint Or NumberStyles.AllowThousands Or _
               NumberStyles.AllowExponent
      provider = CultureInfo.CreateSpecificCulture("en-GB") 
      temp = Temperature.Parse(value, styles, provider)
      Console.WriteLine("{0} degrees Fahrenheit equals {1} degrees Celsius.", _
                        temp.Fahrenheit.ToString("N"), temp.Celsius.ToString("N"))
                                
   End Sub
End Module

注釈

.NET Core 3.0 以降では、表すには大きすぎる値は、IEEE 754 仕様で必要に応じて または NegativeInfinityPositiveInfinity丸められます。 .NET Frameworkを含む以前のバージョンでは、大きすぎる値を解析するとエラーが発生しました。

パラメーターは style 、解析操作を成功させるために パラメーターで s 許可されるスタイル要素 (空白、桁区切り記号、通貨記号など) を定義します。 列挙からのビット フラグ NumberStyles の組み合わせである必要があります。 次 NumberStyles のメンバーはサポートされていません。

パラメーターにはs、 でprovider指定されたカルチャの 、NumberFormatInfo.NegativeInfinitySymbol、または NumberFormatInfo.NaNSymbol を含NumberFormatInfo.PositiveInfinitySymbolめることができます。 の style値に応じて、次の形式を使用することもできます。

[ws][$] [sign][integral-digits,]integral-digits[.[小数部]][E[sign]exponential-digits][ws]

角かっこ ([ と ]) で囲まれた要素は省略可能です。 次の表は、それぞれの要素の説明です。

要素 説明
ws 一連の空白文字。 空白は、 フラグを含む場合は のs先頭に表示でき、フラグが含NumberStyles.AllowLeadingWhiteまれている場合styleは のs末尾にNumberStyles.AllowTrailingWhite表示styleできます。
$ カルチャ固有の通貨記号。 文字列内での位置は、現在のカルチャの NumberFormatInfo.CurrencyNegativePattern プロパティと NumberFormatInfo.CurrencyPositivePattern プロパティによって定義されます。 フラグが含まれている場合styleは、現在のカルチャの通貨記号を にsNumberStyles.AllowCurrencySymbol表示できます。
sign 負符号記号 (-) または正符号記号 (+)。 記号は、 フラグを含む場合は のs先頭に表示でき、フラグが含NumberStyles.AllowLeadingSignまれている場合styleは のs末尾にNumberStyles.AllowTrailingSign表示styleできます。 に フラグが含まれている場合style、かっこを使用sして負の値をNumberStyles.AllowParentheses示すことができます。
整数桁 数値の整数部分を指定する 0 から 9 までの一連の数字。 文字列に小 数部の 要素が含まれている場合、整数 要素は存在しない可能性があります。
, カルチャ固有のグループ区切り記号。 現在のカルチャのグループ区切り記号は、 フラグが含まれている場合stylesNumberStyles.AllowThousandsに表示できます
. カルチャ固有の小数点記号。 現在のカルチャの小数点記号は、 フラグが含まれている場合styleNumberStyles.AllowDecimalPointsに表示できます。
小数部の数字 数値の小数部を指定する 0 から 9 までの一連の数字。 フラグが含まれている場合style、小数部の数字を にsNumberStyles.AllowDecimalPoint表示できます。
E "e" または "E" 文字。値が指数 (指数) 表記で表されることを示します。 フラグが含まれている場合style、パラメーターはs指数表記で数値をNumberStyles.AllowExponent表すことができます。
exponential-digits 指数を指定する 0 から 9 までの一連の数字。

Note

の終端 NUL (U+0000) 文字 s は、引数の style 値に関係なく、解析操作では無視されます。

数字のみを含む文字列 (スタイルに NumberStyles.None 対応) は、型の Double 範囲内にある場合は常に正常に解析されます。 残りの System.Globalization.NumberStyles メンバーは、入力文字列内に存在する可能性がありますが、存在する必要がない要素を制御します。 次の表は、個々 NumberStyles のフラグが に s存在する可能性がある要素に与える影響を示しています。

NumberStyles 値 数字に加えて許可される s 要素
None 整数桁要素のみ。
AllowDecimalPoint 小数点 (.) と 小数部の要素
AllowExponent 指数表記を示す "e" または "E" 文字。 このフラグ自体は、E の形式の値をサポートします。正符号や負符号、小数点記号などの要素を使用して文字列を正常に解析するには、追加のフラグが必要です。
AllowLeadingWhite の先頭sにある ws 要素。
AllowTrailingWhite の末尾sにある ws 要素。
AllowLeadingSign の先頭sにある sign 要素。
AllowTrailingSign の末尾sにある sign 要素。
AllowParentheses 数値を囲むかっこの形式の 符号 要素。
AllowThousands 桁区切り記号 (,) 要素。
AllowCurrencySymbol currency ($) 要素。
Currency すべての要素。 ただし、 s 指数表記で 16 進数または数値を表すことはできません。
Float の先頭または末尾にある sws 要素、の先頭にs記号を付け、小数点 (.) 記号を指定します。 パラメーターでは s 指数表記を使用することもできます。
Number wssign、桁区切り記号 (、) および小数点 (.) 要素。
Any すべての要素。 ただし、 s 16 進数を表すことはできません。

パラメーターはprovider、 の形式sIFormatProvider解釈に使用されるカルチャ固有の情報を提供する オブジェクトをメソッドが返すNumberFormatInfo実装GetFormatです。 通常は、 または CultureInfo オブジェクトですNumberFormatInfo。 が null の場合、または がNumberFormatInfo取得できない場合providerは、現在のシステム カルチャの書式設定情報が使用されます。

通常、 メソッドを Double.Parse 呼び出して作成された文字列をメソッドに Double.ToString 渡すと、元 Double の値が返されます。 ただし、精度が失われるため、値が等しくない可能性があります。 さらに、 または のいずれかのMinValueDouble.MaxValue文字列表現を解析しようとすると、ラウンド トリップに失敗します。 .NET Framework および .NET Core 2.2 以前のバージョンでは、 がスローされますOverflowException。 .NET Core 3.0 以降のバージョンでは、解析を試みた場合、または Double.PositiveInfinity を解析MinValueしようとすると MaxValueが返Double.NegativeInfinityされます。 具体的な例を次に示します。

   string value;

   value = Double.MinValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   value = Double.MaxValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   // Format without the default precision.
   value = Double.MinValue.ToString("G17");
   try
   {
       Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException)
   {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }
// The example displays the following output:
//    -1.79769313486232E+308 is outside the range of the Double type.
//    1.79769313486232E+308 is outside the range of the Double type.
//    -1.79769313486232E+308
open System

[<EntryPoint>]
let main _ =
    let value = string Double.MinValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    let value = string Double.MaxValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    // Format without the default precision.
    let value = Double.MinValue.ToString "G17"
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    0
// The example displays the following output:
//    -1.79769313486232E+308 is outside the range of the Double type.
//    1.79769313486232E+308 is outside the range of the Double type.
//    -1.79769313486232E+308
Dim value As String

value = Double.MinValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

value = Double.MaxValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

' Format without the default precision.
value = Double.MinValue.ToString("G17")
Try 
    Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
' The example displays the following output:
'    -1.79769313486232E+308 is outside the range of the Double type.
'    1.79769313486232E+308 is outside the range of the Double type.            
'    -1.79769313486232E+308

.NET Framework および .NET Core 2.2 以前のバージョンでは、 がデータ型の範囲外のDouble場合sParse(String, NumberStyles, IFormatProvider) メソッドは をOverflowExceptionスローします。

.NET Core 3.0 以降のバージョンでは、 がデータ型の範囲外Doubleの場合s、例外はスローされません。 ほとんどの場合、 メソッドは Parse(String, NumberStyles, IFormatProvider) または Double.NegativeInfinityを返Double.PositiveInfinityします。 ただし、正または負の無限大よりも の最大値または最小値に近いと見なされる値の Double 小さなセットがあります。 そのような場合、 メソッドは または Double.MinValueを返しますDouble.MaxValue

解析操作中にパラメーターで s 区切り記号が検出され、該当する通貨または数値の小数点とグループ区切り記号が同じである場合、解析操作では、区切り記号がグループ区切り記号ではなく小数点の区切り記号であると見なされます。 区切り記号の詳細については、「、、、および 」を参照してくださいCurrencyDecimalSeparatorCurrencyGroupSeparatorNumberDecimalSeparatorNumberGroupSeparator

こちらもご覧ください

適用対象

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

指定したスタイルおよびカルチャ固有の書式による数値の文字列表現を含む文字スパンを、等価の倍精度浮動小数点数に変換します。

public static double Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.Float, IFormatProvider? provider = default);
public static double Parse (ReadOnlySpan<char> s, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.Float, IFormatProvider provider = default);
static member Parse : ReadOnlySpan<char> * System.Globalization.NumberStyles * IFormatProvider -> double
Public Shared Function Parse (s As ReadOnlySpan(Of Char), Optional style As NumberStyles = System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.Float, Optional provider As IFormatProvider = Nothing) As Double

パラメーター

s
ReadOnlySpan<Char>

変換する数値を含む文字スパン。

style
NumberStyles

s で使用可能なスタイル要素を示す、列挙値のビットごとの組み合わせ。 通常指定する値は、AllowThousands と組み合わせた Float です。

provider
IFormatProvider

s に関するカルチャ固有の書式情報を提供するオブジェクト。

戻り値

s で指定した数値または記号と等価の倍精度浮動小数点数。

実装

例外

s が数値を表していません。

styleNumberStyles 値ではありません。

または

styleAllowHexSpecifier 値です。

注釈

.NET Core 3.0 以降では、表すには大きすぎる値は、IEEE 754 仕様で必要に応じて または NegativeInfinityPositiveInfinity丸められます。 .NET Frameworkを含む以前のバージョンでは、大きすぎる値を解析するとエラーが発生しました。

がデータ型の範囲外の場合s、 が よりDouble.MinValue小さい場合sは を返しDouble.PositiveInfinity、 が よりDouble.MaxValue大きい場合sは を返Double.NegativeInfinityDoubleします。

適用対象

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

UTF-8 文字のスパンを値に解析します。

public static double Parse (ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.Float, IFormatProvider? provider = default);
static member Parse : ReadOnlySpan<byte> * System.Globalization.NumberStyles * IFormatProvider -> double
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), Optional style As NumberStyles = System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.Float, Optional provider As IFormatProvider = Nothing) As Double

パラメーター

utf8Text
ReadOnlySpan<Byte>

解析する UTF-8 文字のスパン。

style
NumberStyles

utf8Text存在できる数値スタイルのビットごとの組み合わせ。

provider
IFormatProvider

utf8Text に関するカルチャ固有の書式情報を提供するオブジェクト。

戻り値

を解析した utf8Text結果。

実装

適用対象

Parse(String, IFormatProvider)

指定したカルチャに固有の書式による数値の文字列形式を、それと等価な倍精度浮動小数点数に変換します。

public:
 static double Parse(System::String ^ s, IFormatProvider ^ provider);
public:
 static double Parse(System::String ^ s, IFormatProvider ^ provider) = IParsable<double>::Parse;
public static double Parse (string s, IFormatProvider provider);
public static double Parse (string s, IFormatProvider? provider);
static member Parse : string * IFormatProvider -> double
Public Shared Function Parse (s As String, provider As IFormatProvider) As Double

パラメーター

s
String

変換する数値を含んだ文字列。

provider
IFormatProvider

s に関するカルチャ固有の書式情報を提供するオブジェクト。

戻り値

s で指定した数値または記号と等価の倍精度浮動小数点数。

実装

例外

snullです。

s は有効な形式で数値を表していません。

.NET Frameworkおよび .NET Core 2.2 以前のバージョンのみ: sDouble.MinValue より小さい数値または Double.MaxValue より大きい数値を表します。

次の例は、Web フォームのボタン クリック イベント ハンドラーです。 プロパティによって返される配列を HttpRequest.UserLanguages 使用して、ユーザーのロケールを決定します。 その後、そのロケールに CultureInfo 対応する オブジェクトをインスタンス化します。 NumberFormatInfoそのCultureInfoオブジェクトに属する オブジェクトが メソッドにParse(String, IFormatProvider)渡され、ユーザーの入力が値にDouble変換されます。

protected void OkToDouble_Click(object sender, EventArgs e)
{
    string locale;
    double number;
    CultureInfo culture;

    // Return if string is empty
    if (String.IsNullOrEmpty(this.inputNumber.Text))
        return;

    // Get locale of web request to determine possible format of number
    if (Request.UserLanguages.Length == 0)
        return;
    locale = Request.UserLanguages[0];
    if (String.IsNullOrEmpty(locale))
        return;

    // Instantiate CultureInfo object for the user's locale
    culture = new CultureInfo(locale);

    // Convert user input from a string to a number
    try
    {
        number = Double.Parse(this.inputNumber.Text, culture.NumberFormat);
    }
    catch (FormatException)
    {
        return;
    }
    catch (OverflowException)
    {
        return;
    }
    // Output number to label on web form
    this.outputNumber.Text = "Number is " + number.ToString();
}
Protected Sub OkToDouble_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles OkToDouble.Click
   Dim locale As String
   Dim culture As CultureInfo
   Dim number As Double

   ' Return if string is empty
   If String.IsNullOrEmpty(Me.inputNumber.Text) Then Exit Sub
   
   ' Get locale of web request to determine possible format of number
   If Request.UserLanguages.Length = 0 Then Exit Sub
   locale = Request.UserLanguages(0)
   If String.IsNullOrEmpty(locale) Then Exit Sub

   ' Instantiate CultureInfo object for the user's locale
   culture = New CultureInfo(locale)

   ' Convert user input from a string to a number
   Try
      number = Double.Parse(Me.inputNumber.Text, culture.NumberFormat)
   Catch ex As FormatException
      Exit Sub
   Catch ex As Exception
      Exit Sub
   End Try

   ' Output number to label on web form
   Me.outputNumber.Text = "Number is " & number.ToString()
End Sub

注釈

.NET Core 3.0 以降では、表すには大きすぎる値は、IEEE 754 仕様で必要に応じて または NegativeInfinityPositiveInfinity丸められます。 .NET Frameworkを含む以前のバージョンでは、大きすぎる値を解析するとエラーが発生しました。

メソッドの Parse(String, IFormatProvider) このオーバーロードは、通常、さまざまな方法で書式設定できるテキストを値に変換するために Double 使用されます。 たとえば、ユーザーが入力したテキストを HTML テキスト ボックスに数値に変換するために使用できます。

パラメーターはs、 フラグと NumberStyles.AllowThousands フラグのNumberStyles.Float組み合わせを使用して解釈されます。 パラメーターにはs、 で指定されたproviderカルチャの 、NumberFormatInfo.NegativeInfinitySymbol、または NumberFormatInfo.NaNSymbol を含NumberFormatInfo.PositiveInfinitySymbolめることができます。または、次の形式の文字列を含めることができます。

[ws][sign]integral-digits[.[小数部]][E[sign]exponential-digits][ws]

省略可能な要素は、角かっこ ([ と ]) で囲まれます。 "digits" という用語を含む要素は、0 から 9 までの一連の数字で構成されます。

要素 説明
ws 一連の空白文字。
sign 負符号記号 (-) または正符号記号 (+)。
整数桁 数値の整数部分を指定する 0 から 9 までの一連の数字。 整数桁の実行は、グループ区切り記号でパーティション分割できます。 たとえば、一部のカルチャでは、コンマ (,) は数千のグループを区切ります。 整数桁要素は、文字列に小数部の要素が含まれている場合は存在しない可能性があります。
. カルチャ固有の小数点記号。
小数部の桁数 数値の小数部を指定する 0 から 9 までの一連の数字。
E "e" または "E" 文字。値が指数 (指数) 表記で表されることを示します。
exponential-digits 指数を指定する 0 ~ 9 の範囲の一連の数字。

数値書式の詳細については、「 書式の種類 」トピックを参照してください。

パラメーターはproviderIFormatProviderGetFormat形式sの解釈に使用されるカルチャ固有の情報をNumberFormatInfo提供する オブジェクトをメソッドが返す実装です。 通常は、 または CultureInfo オブジェクトですNumberFormatInfo。 が null または をNumberFormatInfo取得できない場合providerは、現在のシステム カルチャの書式設定情報が使用されます。

通常、メソッドを Double.Parse 呼び出して作成された文字列をメソッドに Double.ToString 渡すと、元 Double の値が返されます。 ただし、精度が失われるため、値が等しくない可能性があります。 さらに、 または Double.MaxValue のいずれかのDouble.MinValue文字列表現を解析しようとすると、ラウンド トリップに失敗します。 .NET Framework および .NET Core 2.2 以前のバージョンでは、 がOverflowExceptionスローされます。 .NET Core 3.0 以降のバージョンでは、 を解析しようとした場合、または Double.PositiveInfinity を解析MinValueしようとすると MaxValueが返Double.NegativeInfinityされます。 具体的な例を次に示します。

   string value;

   value = Double.MinValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   value = Double.MaxValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   // Format without the default precision.
   value = Double.MinValue.ToString("G17");
   try
   {
       Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException)
   {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }
// The example displays the following output:
//    -1.79769313486232E+308 is outside the range of the Double type.
//    1.79769313486232E+308 is outside the range of the Double type.
//    -1.79769313486232E+308
open System

[<EntryPoint>]
let main _ =
    let value = string Double.MinValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    let value = string Double.MaxValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    // Format without the default precision.
    let value = Double.MinValue.ToString "G17"
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    0
// The example displays the following output:
//    -1.79769313486232E+308 is outside the range of the Double type.
//    1.79769313486232E+308 is outside the range of the Double type.
//    -1.79769313486232E+308
Dim value As String

value = Double.MinValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

value = Double.MaxValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

' Format without the default precision.
value = Double.MinValue.ToString("G17")
Try 
    Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
' The example displays the following output:
'    -1.79769313486232E+308 is outside the range of the Double type.
'    1.79769313486232E+308 is outside the range of the Double type.            
'    -1.79769313486232E+308

.NET Framework および .NET Core 2.2 以前のバージョンでは、 がデータ型の範囲外のDouble場合sParse(String, IFormatProvider) メソッドは をOverflowExceptionスローします。

.NET Core 3.0 以降のバージョンでは、 がデータ型の範囲外Doubleの場合s、例外はスローされません。 ほとんどの場合、 メソッドは Parse(String, IFormatProvider) または Double.NegativeInfinityを返Double.PositiveInfinityします。 ただし、正または負の無限大よりも の最大値または最小値に近いと見なされる値の Double 小さなセットがあります。 そのような場合、 メソッドは または Double.MinValueを返しますDouble.MaxValue

解析操作中にパラメーターで s 区切り記号が検出され、該当する通貨または数値の小数点とグループ区切り記号が同じである場合、解析操作では、区切り記号がグループ区切り記号ではなく小数点の区切り記号であると見なされます。 区切り記号の詳細については、「、、、および 」を参照してくださいCurrencyDecimalSeparatorCurrencyGroupSeparatorNumberDecimalSeparatorNumberGroupSeparator

こちらもご覧ください

適用対象

Parse(String)

数値の文字列形式を、等価の倍精度浮動小数点数に変換します。

public:
 static double Parse(System::String ^ s);
public static double Parse (string s);
static member Parse : string -> double
Public Shared Function Parse (s As String) As Double

パラメーター

s
String

変換する数値を含んだ文字列。

戻り値

s で指定した数値または記号と等価の倍精度浮動小数点数。

例外

snullです。

s は有効な形式で数値を表していません。

.NET Frameworkおよび .NET Core 2.2 以前のバージョンのみ: sDouble.MinValue より小さい数値または Double.MaxValue より大きい数値を表します。

Parse(String) メソッドの使用例を次に示します。

public ref class Temperature
{
   // Parses the temperature from a string in form
   // [ws][sign]digits['F|'C][ws]
public:
   static Temperature^ Parse( String^ s )
   {
      Temperature^ temp = gcnew Temperature;
      if ( s->TrimEnd(nullptr)->EndsWith( "'F" ) )
      {
         temp->Value = Double::Parse( s->Remove( s->LastIndexOf( '\'' ), 2 ) );
      }
      else
      if ( s->TrimEnd(nullptr)->EndsWith( "'C" ) )
      {
         temp->Celsius = Double::Parse( s->Remove( s->LastIndexOf( '\'' ), 2 ) );
      }
      else
      {
         temp->Value = Double::Parse( s );
      }

      return temp;
   }

protected:
   // The value holder
   double m_value;

public:
   property double Value 
   {
      double get()
      {
         return m_value;
      }
      void set( double value )
      {
         m_value = value;
      }
   }

   property double Celsius 
   {
      double get()
      {
         return (m_value - 32.0) / 1.8;
      }
      void set( double value )
      {
         m_value = 1.8 * value + 32.0;
      }
   }
};
public class Temperature {
    // Parses the temperature from a string in form
    // [ws][sign]digits['F|'C][ws]
    public static Temperature Parse(string s) {
        Temperature temp = new Temperature();

        if( s.TrimEnd(null).EndsWith("'F") ) {
            temp.Value = Double.Parse( s.Remove(s.LastIndexOf('\''), 2) );
        }
        else if( s.TrimEnd(null).EndsWith("'C") ) {
            temp.Celsius = Double.Parse( s.Remove(s.LastIndexOf('\''), 2) );
        }
        else {
            temp.Value = Double.Parse(s);
        }

        return temp;
    }

    // The value holder
    protected double m_value;

    public double Value {
        get {
            return m_value;
        }
        set {
            m_value = value;
        }
    }

    public double Celsius {
        get {
            return (m_value-32.0)/1.8;
        }
        set {
            m_value = 1.8*value+32.0;
        }
    }
}
type Temperature() =
    // Parses the temperature from a string in form
    // [ws][sign]digits['F|'C][ws]
    static member Parse(s: string) =
        let temp = Temperature()

        if s.TrimEnd(null).EndsWith "'F" then
            temp.Value <- Double.Parse(s.Remove(s.LastIndexOf '\'', 2) )
        elif s.TrimEnd(null).EndsWith "'C" then
            temp.Celsius <- Double.Parse(s.Remove(s.LastIndexOf '\'', 2) )
        else
            temp.Value <- Double.Parse s
        temp

    member val Value = 0. with get, set

    member this.Celsius
        with get () =
            (this.Value - 32.) / 1.8
        and set (value) =
            this.Value <- 1.8 * value + 32.
Public Class Temperature
    ' Parses the temperature from a string in form
    ' [ws][sign]digits['F|'C][ws]
    Public Shared Function Parse(ByVal s As String) As Temperature
        Dim temp As New Temperature()

        If s.TrimEnd(Nothing).EndsWith("'F") Then
            temp.Value = Double.Parse(s.Remove(s.LastIndexOf("'"c), 2))
        Else
            If s.TrimEnd(Nothing).EndsWith("'C") Then
                temp.Celsius = Double.Parse(s.Remove(s.LastIndexOf("'"c), 2))
            Else
                temp.Value = Double.Parse(s)
            End If
        End If
        Return temp
    End Function 'Parse

    ' The value holder
    Protected m_value As Double

    Public Property Value() As Double
        Get
            Return m_value
        End Get
        Set(ByVal Value As Double)
            m_value = Value
        End Set
    End Property

    Public Property Celsius() As Double
        Get
            Return (m_value - 32) / 1.8
        End Get
        Set(ByVal Value As Double)
            m_value = Value * 1.8 + 32
        End Set
    End Property
End Class

注釈

.NET Core 3.0 以降では、表すには大きすぎる値は、IEEE 754 仕様で必要に応じて または NegativeInfinityPositiveInfinity丸められます。 .NET Frameworkを含む以前のバージョンでは、大きすぎる値を解析するとエラーが発生しました。

パラメーターには s 、現在のカルチャの NumberFormatInfo.PositiveInfinitySymbolNumberFormatInfo.NegativeInfinitySymbolNumberFormatInfo.NaNSymbol、または形式の文字列を含めることができます。

[ws][sign][整数桁[,]]integral-digits[.[小数部]][E[sign]exponential-digits][ws]

角かっこ ([ および ]) 内の要素は省略可能です。 次の表は、それぞれの要素の説明です。

要素 説明
ws 一連の空白文字。
sign 負符号記号 (-) または正符号記号 (+)。 先頭の記号のみを使用できます。
整数桁 数値の整数部分を指定する 0 から 9 までの一連の数字。 整数桁の実行は、グループ区切り記号でパーティション分割できます。 たとえば、一部のカルチャでは、コンマ (,) は数千のグループを区切ります。 文字列に小 数部の 要素が含まれている場合、整数 要素は存在しない可能性があります。
, カルチャ固有の桁区切り記号。
. カルチャ固有の小数点記号。
小数部の数字 数値の小数部を指定する 0 から 9 までの一連の数字。
E "e" または "E" 文字。値が指数 (指数) 表記で表されることを示します。
exponential-digits 指数を指定する 0 から 9 までの一連の数字。

パラメーターはs、 フラグと NumberStyles.AllowThousands フラグのNumberStyles.Float組み合わせを使用して解釈されます。 つまり、空白と桁区切り記号は許可されますが、通貨記号は許可されません。 解析操作を成功させるために許可されるsスタイル要素を細かく制御するには、 メソッドまたは メソッドをDouble.Parse(String, NumberStyles, IFormatProvider)呼び出Double.Parse(String, NumberStyles)します。

パラメーターは s 、現在のカルチャ用に初期化されたオブジェクトの NumberFormatInfo 書式設定情報を使用して解釈されます。 詳細については、「CurrentInfo」を参照してください。 他のカルチャの書式設定情報を使用して文字列を解析するには、 メソッドまたは Double.Parse(String, NumberStyles, IFormatProvider) メソッドをDouble.Parse(String, IFormatProvider)呼び出します。

通常、 メソッドを Double.Parse 呼び出して作成された文字列をメソッドに Double.ToString 渡すと、元 Double の値が返されます。 ただし、.NET Frameworkおよび .NET Core 2.2 以前のバージョンでは、精度が低下するため、値が等しくない可能性があります。 さらに、 または のいずれかのDouble.MinValueDouble.MaxValue文字列表現を解析しようとすると、ラウンド トリップに失敗します。 .NET Framework および .NET Core 2.2 以前のバージョンでは、 がスローされますOverflowException。 具体的な例を次に示します。

   string value;

   value = Double.MinValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   value = Double.MaxValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   // Format without the default precision.
   value = Double.MinValue.ToString("G17");
   try
   {
       Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException)
   {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }
// The example displays the following output:
//    -1.79769313486232E+308 is outside the range of the Double type.
//    1.79769313486232E+308 is outside the range of the Double type.
//    -1.79769313486232E+308
open System

[<EntryPoint>]
let main _ =
    let value = string Double.MinValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    let value = string Double.MaxValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    // Format without the default precision.
    let value = Double.MinValue.ToString "G17"
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    0
// The example displays the following output:
//    -1.79769313486232E+308 is outside the range of the Double type.
//    1.79769313486232E+308 is outside the range of the Double type.
//    -1.79769313486232E+308
Dim value As String

value = Double.MinValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

value = Double.MaxValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

' Format without the default precision.
value = Double.MinValue.ToString("G17")
Try 
    Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
' The example displays the following output:
'    -1.79769313486232E+308 is outside the range of the Double type.
'    1.79769313486232E+308 is outside the range of the Double type.            
'    -1.79769313486232E+308

.NET Framework および .NET Core 2.2 以前のバージョンでは、 がデータ型の範囲外のDouble場合sParse(String) メソッドは をOverflowExceptionスローします。

.NET Core 3.0 以降のバージョンでは、 がデータ型の範囲外Doubleである場合s、例外はスローされません。 ほとんどの場合、 メソッドは または Double.NegativeInfinityを返Double.PositiveInfinityします。 ただし、正または負の無限大よりも、 の最大値または最小値に近いと見なされる値の Double 小さなセットがあります。 このような場合、 メソッドは または Double.MinValueを返しますDouble.MaxValue

解析操作中にパラメーターで s 区切り記号が検出され、該当する通貨または数値の小数点とグループの区切り記号が同じ場合、解析操作では、区切り記号がグループ区切り記号ではなく小数点の区切り記号であると見なされます。 区切り記号の詳細については、「、、、および 」を参照してくださいCurrencyDecimalSeparatorCurrencyGroupSeparatorNumberDecimalSeparatorNumberGroupSeparator

こちらもご覧ください

適用対象

Parse(ReadOnlySpan<Char>, IFormatProvider)

文字のスパンを値に解析します。

public:
 static double Parse(ReadOnlySpan<char> s, IFormatProvider ^ provider) = ISpanParsable<double>::Parse;
public static double Parse (ReadOnlySpan<char> s, IFormatProvider? provider);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> double
Public Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As Double

パラメーター

s
ReadOnlySpan<Char>

解析する文字のスパン。

provider
IFormatProvider

s に関するカルチャ固有の書式情報を提供するオブジェクト。

戻り値

を解析した s結果。

実装

適用対象

Parse(ReadOnlySpan<Byte>, IFormatProvider)

UTF-8 文字のスパンを値に解析します。

public:
 static double Parse(ReadOnlySpan<System::Byte> utf8Text, IFormatProvider ^ provider) = IUtf8SpanParsable<double>::Parse;
public static double Parse (ReadOnlySpan<byte> utf8Text, IFormatProvider? provider);
static member Parse : ReadOnlySpan<byte> * IFormatProvider -> double
Public Shared Function Parse (utf8Text As ReadOnlySpan(Of Byte), provider As IFormatProvider) As Double

パラメーター

utf8Text
ReadOnlySpan<Byte>

解析する UTF-8 文字のスパン。

provider
IFormatProvider

utf8Text に関するカルチャ固有の書式情報を提供するオブジェクト。

戻り値

を解析した utf8Text結果。

実装

適用対象

Parse(String, NumberStyles)

数値の指定したスタイルでの文字列形式を、それと等価な倍精度浮動小数点数に変換します。

public:
 static double Parse(System::String ^ s, System::Globalization::NumberStyles style);
public static double Parse (string s, System.Globalization.NumberStyles style);
static member Parse : string * System.Globalization.NumberStyles -> double
Public Shared Function Parse (s As String, style As NumberStyles) As Double

パラメーター

s
String

変換する数値を含んだ文字列。

style
NumberStyles

s で使用可能なスタイル要素を示す、列挙値のビットごとの組み合わせ。 通常指定する値は、FloatAllowThousands の組み合わせです。

戻り値

s で指定した数値または記号と等価の倍精度浮動小数点数。

例外

snullです。

s は有効な形式で数値を表していません。

.NET Framework および .NET Core 2.2 以前のバージョンのみ: sDouble.MinValue より小さいか、Double.MaxValue より大きい数値を表します。

styleNumberStyles 値ではありません。

または

style には値 AllowHexSpecifier が含まれています。

次の例では、 メソッドを Parse(String, NumberStyles) 使用して、en-US カルチャを使用して値の Double 文字列表現を解析します。

public static void Main()
{
   // Set current thread culture to en-US.
   Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");

   string value;
   NumberStyles styles;

   // Parse a string in exponential notation with only the AllowExponent flag.
   value = "-1.063E-02";
   styles = NumberStyles.AllowExponent;
   ShowNumericValue(value, styles);

   // Parse a string in exponential notation
   // with the AllowExponent and Number flags.
   styles = NumberStyles.AllowExponent | NumberStyles.Number;
   ShowNumericValue(value, styles);

   // Parse a currency value with leading and trailing white space, and
   // white space after the U.S. currency symbol.
   value = " $ 6,164.3299  ";
   styles = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
   ShowNumericValue(value, styles);

   // Parse negative value with thousands separator and decimal.
   value = "(4,320.64)";
   styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign |
            NumberStyles.Float;
   ShowNumericValue(value, styles);

   styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign |
            NumberStyles.Float | NumberStyles.AllowThousands;
   ShowNumericValue(value, styles);
}

private static void ShowNumericValue(string value, NumberStyles styles)
{
   double number;
   try
   {
      number = Double.Parse(value, styles);
      Console.WriteLine("Converted '{0}' using {1} to {2}.",
                        value, styles.ToString(), number);
   }
   catch (FormatException)
   {
      Console.WriteLine("Unable to parse '{0}' with styles {1}.",
                        value, styles.ToString());
   }
   Console.WriteLine();
}
// The example displays the following output to the console:
//    Unable to parse '-1.063E-02' with styles AllowExponent.
//
//    Converted '-1.063E-02' using AllowTrailingSign, AllowThousands, Float to -0.01063.
//
//    Converted ' $ 6,164.3299  ' using Number, AllowCurrencySymbol to 6164.3299.
//
//    Unable to parse '(4,320.64)' with styles AllowTrailingSign, AllowParentheses, Float.
//
//    Converted '(4,320.64)' using AllowTrailingSign, AllowParentheses, AllowThousands, Float to -4320.64.
open System
open System.Globalization
open System.Threading

let showNumericValue (value: string) (styles: NumberStyles) =
    try
        let number = Double.Parse(value, styles)
        printfn $"Converted '{value}' using {styles} to {number}."
    with :? FormatException ->
        printfn $"Unable to parse '{value}' with styles {styles}."
    printfn ""

[<EntryPoint>]
let main _ =
    // Set current thread culture to en-US.
    Thread.CurrentThread.CurrentCulture <- CultureInfo.CreateSpecificCulture "en-US"

    // Parse a string in exponential notation with only the AllowExponent flag.
    let value = "-1.063E-02"
    let styles = NumberStyles.AllowExponent
    showNumericValue value styles

    // Parse a string in exponential notation
    // with the AllowExponent and Number flags.
    let styles = NumberStyles.AllowExponent ||| NumberStyles.Number
    showNumericValue value styles

    // Parse a currency value with leading and trailing white space, and
    // white space after the U.S. currency symbol.
    let value = " $ 6,164.3299  "
    let styles = NumberStyles.Number ||| NumberStyles.AllowCurrencySymbol
    showNumericValue value styles

    // Parse negative value with thousands separator and decimal.
    let value = "(4,320.64)"
    let styles = 
        NumberStyles.AllowParentheses ||| NumberStyles.AllowTrailingSign ||| NumberStyles.Float
    showNumericValue value styles

    let styles = 
        NumberStyles.AllowParentheses ||| NumberStyles.AllowTrailingSign ||| NumberStyles.Float ||| NumberStyles.AllowThousands
    showNumericValue value styles

    0

// The example displays the following output to the console:
//    Unable to parse '-1.063E-02' with styles AllowExponent.
//
//    Converted '-1.063E-02' using AllowTrailingSign, AllowThousands, Float to -0.01063.
//
//    Converted ' $ 6,164.3299  ' using Number, AllowCurrencySymbol to 6164.3299.
//
//    Unable to parse '(4,320.64)' with styles AllowTrailingSign, AllowParentheses, Float.
//
//    Converted '(4,320.64)' using AllowTrailingSign, AllowParentheses, AllowThousands, Float to -4320.64.
Public Sub Main()
   ' Set current thread culture to en-US.
   Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US")
         
   Dim value As String
   Dim styles As NumberStyles
   
   ' Parse a string in exponential notation with only the AllowExponent flag. 
   value = "-1.063E-02"
   styles = NumberStyles.AllowExponent
   ShowNumericValue(value, styles) 
   
   ' Parse a string in exponential notation
   ' with the AllowExponent and Number flags.
   styles = NumberStyles.AllowExponent Or NumberStyles.Number
   ShowNumericValue(value, styles)

   ' Parse a currency value with leading and trailing white space, and
   ' white space after the U.S. currency symbol.
   value = " $ 6,164.3299  "
   styles = NumberStyles.Number Or NumberStyles.AllowCurrencySymbol
   ShowNumericValue(value, styles)
   
   ' Parse negative value with thousands separator and decimal.
   value = "(4,320.64)"
   styles = NumberStyles.AllowParentheses Or NumberStyles.AllowTrailingSign _
            Or NumberStyles.Float 
   ShowNumericValue(value, styles)
   
   styles = NumberStyles.AllowParentheses Or NumberStyles.AllowTrailingSign _
            Or NumberStyles.Float Or NumberStyles.AllowThousands
   ShowNumericValue(value, styles)
End Sub

Private Sub ShowNumericValue(value As String, styles As NumberStyles)
   Dim number As Double
   Try
      number = Double.Parse(value, styles)
      Console.WriteLine("Converted '{0}' using {1} to {2}.", _
                        value, styles.ToString(), number)
   Catch e As FormatException
      Console.WriteLine("Unable to parse '{0}' with styles {1}.", _
                        value, styles.ToString())
   End Try
   Console.WriteLine()                           
End Sub
' The example displays the following output to the console:
'    Unable to parse '-1.063E-02' with styles AllowExponent.
'    
'    Converted '-1.063E-02' using AllowTrailingSign, AllowThousands, Float to -0.01063.
'    
'    Converted ' $ 6,164.3299  ' using Number, AllowCurrencySymbol to 6164.3299.
'    
'    Unable to parse '(4,320.64)' with styles AllowTrailingSign, AllowParentheses, Float.
'    
'    Converted '(4,320.64)' using AllowTrailingSign, AllowParentheses, AllowThousands, Float to -4320.64.

注釈

.NET Core 3.0 以降では、表すには大きすぎる値は、IEEE 754 仕様で必要に応じて または NegativeInfinityPositiveInfinity丸められます。 .NET Frameworkを含む以前のバージョンでは、大きすぎる値を解析するとエラーが発生しました。

パラメーターは style 、解析操作を成功させるために パラメーターで s 許可されるスタイル要素 (空白、桁区切り記号、通貨記号など) を定義します。 列挙からのビット フラグ NumberStyles の組み合わせである必要があります。 次 NumberStyles のメンバーはサポートされていません。

パラメーターには s 、現在のカルチャの NumberFormatInfo.PositiveInfinitySymbol、、 NumberFormatInfo.NegativeInfinitySymbolまたは NumberFormatInfo.NaNSymbolを含めることができます。 の style値に応じて、次の形式を使用することもできます。

[ws][$][sign][integral-digits[,]]integral-digits[.[小数部]][E[sign]exponential-digits][ws]

角かっこ ([ および ]) 内の要素は省略可能です。 次の表は、それぞれの要素の説明です。

要素 説明
ws 一連の空白文字。 空白は、 フラグを含む場合は のs先頭に表示でき、フラグが含NumberStyles.AllowLeadingWhiteまれている場合styleは のs末尾にNumberStyles.AllowTrailingWhite表示styleできます。
$ カルチャ固有の通貨記号。 文字列内での位置は、現在のカルチャの NumberFormatInfo.CurrencyNegativePattern プロパティと NumberFormatInfo.CurrencyPositivePattern プロパティによって定義されます。 フラグが含まれている場合styleは、現在のカルチャの通貨記号を にsNumberStyles.AllowCurrencySymbol表示できます。
sign 負符号記号 (-) または正符号記号 (+)。 記号は、 フラグを含む場合は のs先頭に表示でき、フラグが含NumberStyles.AllowLeadingSignまれている場合styleは のs末尾にNumberStyles.AllowTrailingSign表示styleできます。 に フラグが含まれている場合style、かっこを使用sして負の値をNumberStyles.AllowParentheses示すことができます。
整数桁 数値の整数部分を指定する 0 から 9 までの一連の数字。 文字列に小 数部の 要素が含まれている場合、整数 要素は存在しない可能性があります。
, カルチャ固有のグループ区切り記号。 現在のカルチャのグループ区切り記号は、 フラグが含まれている場合stylesNumberStyles.AllowThousandsに表示できます
. カルチャ固有の小数点記号。 現在のカルチャの小数点記号は、 フラグが含まれている場合styleNumberStyles.AllowDecimalPointsに表示できます。
小数部の数字 数値の小数部を指定する 0 から 9 までの一連の数字。 フラグが含まれている場合style、小数部の数字を にsNumberStyles.AllowDecimalPoint表示できます。
E "e" または "E" 文字。値が指数 (指数) 表記で表されることを示します。 フラグが含まれている場合style、パラメーターはs指数表記で数値をNumberStyles.AllowExponent表すことができます。
exponential-digits 指数を指定する 0 から 9 までの一連の数字。

Note

の終端 NUL (U+0000) 文字 s は、引数の style 値に関係なく、解析操作では無視されます。

数字のみを含む文字列 (スタイルに NumberStyles.None 対応) は、型の Double 範囲内にある場合は常に正常に解析されます。 残りの System.Globalization.NumberStyles メンバーは、入力文字列内に存在する可能性がありますが、存在する必要がない要素を制御します。 次の表は、個々 NumberStyles のフラグが に s存在する可能性がある要素に与える影響を示しています。

NumberStyles 値 数字に加えて許可される s 要素
None 整数桁要素のみ。
AllowDecimalPoint 小数点 (.) 要素と 小数部の要素
AllowExponent 指数表記を示す "e" または "E" 文字。 このフラグ自体では、E の形式の値がサポートされます。正符号や負符号、小数点記号などの要素を含む文字列を正常に解析するには、追加のフラグが必要です。
AllowLeadingWhite の先頭sにある ws 要素。
AllowTrailingWhite の末尾sにある ws 要素。
AllowLeadingSign の先頭sにある sign 要素。
AllowTrailingSign の末尾sにある sign 要素。
AllowParentheses 数値を囲むかっこの形式の sign 要素。
AllowThousands 桁区切り記号 (,) 要素。
AllowCurrencySymbol currency ($) 要素。
Currency すべての要素。 ただし、 s 16 進数または数値を指数表記で表すことはできません。
Float の先頭または末尾の sws 要素、の先頭のs符号、および小数点 (.) 記号。 パラメーターでは s 、指数表記を使用することもできます。
Number wssign、桁区切り記号 (,) および小数点 (.) 要素。
Any すべての要素。 ただし、 s 16 進数を表すことはできません。

パラメーターは s 、現在のシステム カルチャ用に初期化された オブジェクトの NumberFormatInfo 書式設定情報を使用して解析されます。 詳細については、「CurrentInfo」を参照してください。

通常、メソッドを Double.Parse 呼び出して作成された文字列をメソッドに Double.ToString 渡すと、元 Double の値が返されます。 ただし、精度が失われるため、値が等しくない可能性があります。 さらに、 または Double.MaxValue のいずれかのDouble.MinValue文字列表現を解析しようとすると、ラウンド トリップに失敗します。 .NET Framework および .NET Core 2.2 以前のバージョンでは、 がOverflowExceptionスローされます。 .NET Core 3.0 以降のバージョンでは、 を解析しようとした場合、または Double.PositiveInfinity を解析MinValueしようとすると MaxValueが返Double.NegativeInfinityされます。 具体的な例を次に示します。

   string value;

   value = Double.MinValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   value = Double.MaxValue.ToString();
   try {
      Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException) {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }

   // Format without the default precision.
   value = Double.MinValue.ToString("G17");
   try
   {
       Console.WriteLine(Double.Parse(value));
   }
   catch (OverflowException)
   {
      Console.WriteLine($"{value} is outside the range of the Double type.");
   }
// The example displays the following output:
//    -1.79769313486232E+308 is outside the range of the Double type.
//    1.79769313486232E+308 is outside the range of the Double type.
//    -1.79769313486232E+308
open System

[<EntryPoint>]
let main _ =
    let value = string Double.MinValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    let value = string Double.MaxValue
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    // Format without the default precision.
    let value = Double.MinValue.ToString "G17"
    try
        printfn $"{Double.Parse value}"
    with :? OverflowException ->
        printfn $"{value} is outside the range of the Double type."

    0
// The example displays the following output:
//    -1.79769313486232E+308 is outside the range of the Double type.
//    1.79769313486232E+308 is outside the range of the Double type.
//    -1.79769313486232E+308
Dim value As String

value = Double.MinValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

value = Double.MaxValue.ToString()
Try
   Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try

' Format without the default precision.
value = Double.MinValue.ToString("G17")
Try 
    Console.WriteLine(Double.Parse(value))
Catch e As OverflowException
   Console.WriteLine($"{value} is outside the range of the Double type.")
End Try
' The example displays the following output:
'    -1.79769313486232E+308 is outside the range of the Double type.
'    1.79769313486232E+308 is outside the range of the Double type.            
'    -1.79769313486232E+308

.NET Framework および .NET Core 2.2 以前のバージョンでは、 がデータ型の範囲外のDouble場合sParse(String, NumberStyles) メソッドは をOverflowExceptionスローします。

.NET Core 3.0 以降のバージョンでは、 がデータ型の範囲外Doubleの場合s、例外はスローされません。 ほとんどの場合、 メソッドは Parse(String, NumberStyles) または Double.NegativeInfinityを返Double.PositiveInfinityします。 ただし、正または負の無限大よりも の最大値または最小値に近いと見なされる値の Double 小さなセットがあります。 そのような場合、 メソッドは または Double.MinValueを返しますDouble.MaxValue

解析操作中にパラメーターで s 区切り記号が検出され、該当する通貨または数値の小数点とグループ区切り記号が同じである場合、解析操作では、区切り記号がグループ区切り記号ではなく小数点の区切り記号であると見なされます。 区切り記号の詳細については、「、、、および 」を参照してくださいCurrencyDecimalSeparatorCurrencyGroupSeparatorNumberDecimalSeparatorNumberGroupSeparator

こちらもご覧ください

適用対象