Double.Parse メソッド

定義

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

オーバーロード

Parse(String)

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

Parse(ReadOnlySpan<Byte>, IFormatProvider)

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

Parse(ReadOnlySpan<Char>, IFormatProvider)

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

Parse(String, NumberStyles)

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

Parse(String, IFormatProvider)

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

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

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

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

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

Parse(String, NumberStyles, IFormatProvider)

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

注釈

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

Parse(String)

ソース:
Double.cs
ソース:
Double.cs
ソース:
Double.cs

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

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 以前のバージョンのみ: は、Double.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 仕様で必要に応じて、大きすぎる値は PositiveInfinity または NegativeInfinity に丸められます。 以前のバージョン (.NET Framework を含む) では、大きすぎる値を解析するとエラーが発生しました。

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

[ ws][sign][整数桁[,]]整数桁[.[小数部]][E[符号]指数桁][ws]

角かっこ ([ と ]) の要素は省略可能です。 次の表では、各要素について説明します。

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

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

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

通常、Double.ToString メソッドを呼び出して作成された文字列を Double.Parse メソッドに渡すと、元の Double 値が返されます。 ただし、.NET Framework および .NET Core 2.2 以前のバージョンでは、精度が失われるため、値が等しくない可能性があります。 さらに、Double.MinValue または Double.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 以前のバージョンでは、sDouble データ型の範囲外の場合、Parse(String) メソッドは OverflowExceptionをスローします。

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

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

こちらもご覧ください

適用対象

Parse(ReadOnlySpan<Byte>, IFormatProvider)

ソース:
Double.cs
ソース:
Double.cs

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(ReadOnlySpan<Char>, IFormatProvider)

ソース:
Double.cs
ソース:
Double.cs
ソース:
Double.cs

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

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(String, NumberStyles)

ソース:
Double.cs
ソース:
Double.cs
ソース:
Double.cs

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

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に存在できるスタイル要素を示す列挙値のビットごとの組み合わせ。 指定する一般的な値は、AllowThousandsと組み合わせた Float の組み合わせです。

戻り値

sで指定された数値または記号に相当する倍精度浮動小数点数。

例外

snullです。

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

.NET Framework および .NET Core 2.2 以前のバージョンのみ: は、Double.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 仕様で必要に応じて、大きすぎる値は PositiveInfinity または NegativeInfinity に丸められます。 以前のバージョン (.NET Framework を含む) では、大きすぎる値を解析するとエラーが発生しました。

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

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

[ ws][][sign][整数桁[,]]整数桁[.[小数部]][E[符号]指数桁][ws]

角かっこ ([ と ]) の要素は省略可能です。 次の表では、各要素について説明します。

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

手記

s で終了する NUL (U+0000) 文字は、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の先頭にある 記号 要素です。
AllowTrailingSign の末尾にある要素 記号。
AllowParentheses 符号、数値を囲むかっこの形式で要素に署名します。
AllowThousands 桁区切り記号 (,) 要素。
AllowCurrencySymbol currency ($) 要素。
Currency すべての要素。 ただし、s は、指数表記で 16 進数または数値を表すことはできません。
Float sの先頭または末尾の ws 要素、sの先頭 記号、および小数点 (.) 記号。 s パラメーターでは指数表記を使用することもできます。
Number wssign、桁区切り記号 (、)、小数点 (.) の各要素。
Any すべての要素。 ただし、s は 16 進数を表すことはできません。

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

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

   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 以前のバージョンでは、sDouble データ型の範囲外の場合、Parse(String, NumberStyles) メソッドは OverflowExceptionをスローします。

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

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

こちらもご覧ください

適用対象

Parse(String, IFormatProvider)

ソース:
Double.cs
ソース:
Double.cs
ソース:
Double.cs

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

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 以前のバージョンのみ: は、Double.MinValue 未満の数値、または Double.MaxValueより大きい数値を表します。

次の例は、Web フォームのボタン クリック イベント ハンドラーです。 HttpRequest.UserLanguages プロパティによって返される配列を使用して、ユーザーのロケールを決定します。 その後、そのロケールに対応する CultureInfo オブジェクトをインスタンス化します。 その CultureInfo オブジェクトに属する NumberFormatInfo オブジェクトが 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 仕様で必要に応じて、大きすぎる値は PositiveInfinity または NegativeInfinity に丸められます。 以前のバージョン (.NET Framework を含む) では、大きすぎる値を解析するとエラーが発生しました。

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

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

[ ws][符号]整数桁[.[小数部]][E[符号]指数桁][ws]

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

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

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

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

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

   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 以前のバージョンでは、sDouble データ型の範囲外の場合、Parse(String, IFormatProvider) メソッドは OverflowExceptionをスローします。

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

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

こちらもご覧ください

適用対象

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

ソース:
Double.cs
ソース:
Double.cs

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(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

ソース:
Double.cs
ソース:
Double.cs
ソース:
Double.cs

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

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 仕様で必要に応じて、大きすぎる値は PositiveInfinity または NegativeInfinity に丸められます。 以前のバージョン (.NET Framework を含む) では、大きすぎる値を解析するとエラーが発生しました。

sDouble データ型の範囲外の場合、sDouble.MinValue 未満の場合は Double.NegativeInfinity を返し、sDouble.MaxValueより大きい場合は Double.PositiveInfinity を返します。

適用対象

Parse(String, NumberStyles, IFormatProvider)

ソース:
Double.cs
ソース:
Double.cs
ソース:
Double.cs

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

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 以前のバージョンのみ: は、Double.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 仕様で必要に応じて、大きすぎる値は PositiveInfinity または NegativeInfinity に丸められます。 以前のバージョン (.NET Framework を含む) では、大きすぎる値を解析するとエラーが発生しました。

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

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

[ ws][][sign][整数桁, ]整数桁[.[小数部]][E[符号]指数桁][ws]

角かっこ ([ と ]) で囲まれた要素は省略可能です。 次の表では、各要素について説明します。

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

手記

s で終了する NUL (U+0000) 文字は、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の先頭にある 記号 要素です。
AllowTrailingSign の末尾にある要素 記号。
AllowParentheses 符号、数値を囲むかっこの形式で要素に署名します。
AllowThousands 桁区切り記号 (,) 要素。
AllowCurrencySymbol currency ($) 要素。
Currency すべての要素。 ただし、s は、指数表記で 16 進数または数値を表すことはできません。
Float sの先頭または末尾の ws 要素、sの先頭 記号、および小数点 (.) 記号。 s パラメーターでは指数表記を使用することもできます。
Number wssign、桁区切り記号 (、)、小数点 (.) の各要素。
Any すべての要素。 ただし、s は 16 進数を表すことはできません。

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

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

   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 以前のバージョンでは、sDouble データ型の範囲外の場合、Parse(String, NumberStyles, IFormatProvider) メソッドは OverflowExceptionをスローします。

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

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

こちらもご覧ください

  • ToString()
  • .NET での数値文字列の解析の

適用対象