次の方法で共有


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
ソース:
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 のみ: sは、Double.MinValue 未満または Double.MaxValue より大きい数値表します。

次の例は、 Parse(String) メソッドの使用方法を示しています。

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.NegativeInfinitySymbol、またはNumberFormatInfo.NaNSymbolシンボルを含めることができます。 この文字列比較は、.NET Core 3.0 以降のバージョンでは大文字と小文字は区別されませんが、.NET Framework を含む以前のバージョンでは大文字と小文字が区別されます。 s パラメーターには、次の形式の文字列を指定することもできます。

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

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

要素 形容
ws 一連の空白文字。
サイン 負符号記号 (-) または正符号記号 (+)。 先頭の記号のみを使用できます。
整数桁 数値の整数部分を指定する 0 から 9 までの一連の数字。 整数桁の実行は、グループ区切り記号でパーティション分割できます。 たとえば、一部のカルチャでは、コンマ (,) は数千のグループを区切ります。 整数桁の要素は、文字列に小数部の要素が含まれている場合は使用できません。
, カルチャ固有の桁区切り記号。
. カルチャ固有の小数点記号。
fractional-digits 数値の小数部を指定する 0 から 9 までの一連の数字。
E "e" または "E" 文字。値が指数 (指数) 表記で表されることを示します。
exponential-digits 指数を指定する 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.Parse メソッドを呼び出して作成された文字列をDouble.ToString メソッドに渡すと、元のDouble値が返されます。 ただし、.NET Framework では、精度が失われるため、値が等しくない可能性があります。 さらに、 Double.MinValue または Double.MaxValue の文字列形式を解析しようとすると、ラウンド トリップに失敗します。 .NET Framework では、 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 では、 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
ソース:
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
ソース:
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
ソース:
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に存在できるスタイル要素を示す列挙値のビットごとの組み合わせ。 指定する一般的な値は、 FloatAllowThousandsの組み合わせです。

返品

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

例外

snullです。

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

.NET Framework のみ: sは、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シンボルを含めることができます。 この文字列比較は、.NET Core 3.0 以降のバージョンでは大文字と小文字は区別されませんが、.NET Framework を含む以前のバージョンでは大文字と小文字が区別されます。 styleの値に応じて、s パラメーターは次の形式をとることもできます。

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

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

要素 形容
ws 一連の空白文字。 sstyle フラグが含まれている場合は、NumberStyles.AllowLeadingWhiteの先頭に空白が表示され、sstyle フラグが含まれている場合は、NumberStyles.AllowTrailingWhiteの末尾に空白を表示できます。
$ カルチャ固有の通貨記号。 文字列内での位置は、現在のカルチャの NumberFormatInfo.CurrencyNegativePattern プロパティと NumberFormatInfo.CurrencyPositivePattern プロパティによって定義されます。 現在のカルチャの通貨記号は、s フラグstyle含まれている場合、NumberStyles.AllowCurrencySymbolに表示されます。
サイン 負符号記号 (-) または正符号記号 (+)。 sstyle フラグが含まれている場合はNumberStyles.AllowLeadingSignの先頭に表示され、sstyle フラグが含まれている場合はNumberStyles.AllowTrailingSignの末尾に表示されます。 sでかっこを使用して、styleNumberStyles.AllowParentheses フラグが含まれている場合は負の値を示すことができます。
整数桁 数値の整数部分を指定する 0 から 9 までの一連の数字。 整数桁の要素は、文字列に小数部の要素が含まれている場合は使用できません。
, カルチャ固有のグループ区切り記号。 s フラグが含まれている場合、現在のカルチャのグループ区切り記号styleNumberStyles.AllowThousandsに表示される場合があります
. カルチャ固有の小数点記号。 現在のカルチャの小数点記号は、s フラグstyle含まれている場合、NumberStyles.AllowDecimalPointに表示できます。
fractional-digits 数値の小数部を指定する 0 から 9 までの一連の数字。 sstyle フラグが含まれている場合、小数部の数字はNumberStyles.AllowDecimalPointに表示されます。
E "e" または "E" 文字。値が指数 (指数) 表記で表されることを示します。 s パラメーターは、style フラグが含まれている場合NumberStyles.AllowExponent指数表記で数値を表すことができます。
exponential-digits 指数を指定する 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 要素。
AllowTrailingWhite の末尾にある s 要素。
AllowLeadingSign の先頭にある s 要素。
AllowTrailingSign の末尾にある s 要素。
AllowParentheses 数値を囲むかっこの形式の 符号 要素。
AllowThousands 桁区切り記号 (,) 要素。
AllowCurrencySymbol currency ($) 要素。
Currency すべての要素。 ただし、 s は、指数表記で 16 進数または数値を表すことはできません。
Float の先頭または末尾の s 要素、の先頭のs、および小数点 (.) 記号。 s パラメーターでは指数表記を使用することもできます。
Number wssign、桁区切り記号 (、)、小数点 (.) の各要素。
Any すべての要素。 ただし、 s は 16 進数を表すことはできません。

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

通常、Double.Parse メソッドを呼び出して作成された文字列をDouble.ToString メソッドに渡すと、元のDouble値が返されます。 ただし、精度が失われるため、値が等しくない可能性があります。 さらに、 Double.MinValue または Double.MaxValue の文字列形式を解析しようとすると、ラウンド トリップに失敗します。 .NET Framework では、 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 では、 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
ソース:
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 のみ: sは、Double.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 仕様で必要に応じて、大きすぎる値は PositiveInfinity または NegativeInfinity に丸められます。 以前のバージョン (.NET Framework を含む) では、大きすぎる値を解析するとエラーが発生しました。

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

s パラメーターは、NumberStyles.FloatフラグとNumberStyles.AllowThousands フラグの組み合わせを使用して解釈されます。 s パラメーターには、NumberFormatInfo.PositiveInfinitySymbolで指定されたカルチャのNumberFormatInfo.NegativeInfinitySymbolNumberFormatInfo.NaNSymbol、またはproviderシンボルを含めることができます。 この文字列比較は、.NET Core 3.0 以降のバージョンでは大文字と小文字は区別されませんが、.NET Framework を含む以前のバージョンでは大文字と小文字が区別されます。 s パラメーターには、次の形式の文字列を含めることもできます。

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

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

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

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

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

通常、Double.Parse メソッドを呼び出して作成された文字列をDouble.ToString メソッドに渡すと、元のDouble値が返されます。 ただし、精度が失われるため、値が等しくない可能性があります。 さらに、 Double.MinValue または Double.MaxValue の文字列形式を解析しようとすると、ラウンド トリップに失敗します。 .NET Framework では、 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 では、 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
ソース:
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
ソース:
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に存在できるスタイル要素を示す列挙値のビットごとの組み合わせ。 指定する一般的な値は、Floatと組み合わせてAllowThousands

provider
IFormatProvider

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

返品

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

実装

例外

s は数値を表しません。

styleNumberStyles 値ではありません。

-又は-

styleAllowHexSpecifier 値です。

注釈

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

sDoubleデータ型の範囲外の場合、Double.NegativeInfinitys未満の場合はDouble.MinValueを返し、Double.PositiveInfinitysより大きい場合はDouble.MaxValue

適用対象

Parse(String, NumberStyles, IFormatProvider)

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

provider
IFormatProvider

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

返品

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

実装

例外

snullです。

s は数値を表しません。

styleNumberStyles 値ではありません。

-又は-

styleAllowHexSpecifier 値です。

.NET Framework のみ: sは、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 パラメーターには、NumberFormatInfo.PositiveInfinitySymbolで指定されたカルチャのNumberFormatInfo.NegativeInfinitySymbolNumberFormatInfo.NaNSymbol、またはproviderシンボルを含めることができます。 この文字列比較は、.NET Core 3.0 以降のバージョンでは大文字と小文字は区別されませんが、.NET Framework を含む以前のバージョンでは大文字と小文字が区別されます。 styleの値に応じて、s パラメーターは次の形式をとることもできます。

[ws][$] [sign][integral-digits,]integral-digits[.[fractional-digits]][E[sign]exponential-digits][ws]

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

要素 形容
ws 一連の空白文字。 sstyle フラグが含まれている場合は、NumberStyles.AllowLeadingWhiteの先頭に空白が表示され、sstyle フラグが含まれている場合は、NumberStyles.AllowTrailingWhiteの末尾に空白を表示できます。
$ カルチャ固有の通貨記号。 文字列内での位置は、現在のカルチャの NumberFormatInfo.CurrencyNegativePattern プロパティと NumberFormatInfo.CurrencyPositivePattern プロパティによって定義されます。 現在のカルチャの通貨記号は、s フラグstyle含まれている場合、NumberStyles.AllowCurrencySymbolに表示されます。
サイン 負符号記号 (-) または正符号記号 (+)。 sstyle フラグが含まれている場合はNumberStyles.AllowLeadingSignの先頭に表示され、sstyle フラグが含まれている場合はNumberStyles.AllowTrailingSignの末尾に表示されます。 sでかっこを使用して、styleNumberStyles.AllowParentheses フラグが含まれている場合は負の値を示すことができます。
整数桁 数値の整数部分を指定する 0 から 9 までの一連の数字。 整数桁の要素は、文字列に小数部の要素が含まれている場合は使用できません。
, カルチャ固有のグループ区切り記号。 s フラグが含まれている場合、現在のカルチャのグループ区切り記号styleNumberStyles.AllowThousandsに表示される場合があります
. カルチャ固有の小数点記号。 現在のカルチャの小数点記号は、s フラグstyle含まれている場合、NumberStyles.AllowDecimalPointに表示できます。
fractional-digits 数値の小数部を指定する 0 から 9 までの一連の数字。 sstyle フラグが含まれている場合、小数部の数字はNumberStyles.AllowDecimalPointに表示されます。
E "e" または "E" 文字。値が指数 (指数) 表記で表されることを示します。 s パラメーターは、style フラグが含まれている場合NumberStyles.AllowExponent指数表記で数値を表すことができます。
exponential-digits 指数を指定する 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 要素。
AllowTrailingWhite の末尾にある s 要素。
AllowLeadingSign の先頭にある s 要素。
AllowTrailingSign の末尾にある s 要素。
AllowParentheses 数値を囲むかっこの形式の 符号 要素。
AllowThousands 桁区切り記号 (,) 要素。
AllowCurrencySymbol currency ($) 要素。
Currency すべての要素。 ただし、 s は、指数表記で 16 進数または数値を表すことはできません。
Float の先頭または末尾の s 要素、の先頭のs、および小数点 (.) 記号。 s パラメーターでは指数表記を使用することもできます。
Number wssign、桁区切り記号 (、)、小数点 (.) の各要素。
Any すべての要素。 ただし、 s は 16 進数を表すことはできません。

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

通常、Double.Parse メソッドを呼び出して作成された文字列をDouble.ToString メソッドに渡すと、元のDouble値が返されます。 ただし、精度が失われるため、値が等しくない可能性があります。 さらに、 MinValue または Double.MaxValue の文字列形式を解析しようとすると、ラウンド トリップに失敗します。 .NET Framework では、 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 では、 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」を参照してください。

こちらもご覧ください

適用対象