Tukar String kepada Double dalam C#

WBOY
Lepaskan: 2024-09-03 15:17:06
asal
590 orang telah melayarinya

In C#, almost all types of data can be converted to any other type. In the same way, we can convert a string to double using a method present inside the “Convert” class called ToDouble() method. There are many overloaded forms of this method and among those overloaded forms, we have two forms to convert a string representation of a number to its equivalent double-precision floating-point number.

Those two overloaded forms are as follows:

  • ToDouble(String);
  • ToDouble(String, IFormatProvider);

Both these methods return a double value after converting the string value to double.

Syntax with Explanation:

The syntax of Convert.ToDouble() method in both its overloaded forms for converting a string to double is as follows:

public static double ToDouble(string strValue);
Salin selepas log masuk

In the above syntax, ToDouble() method takes one argument of type string (strValue) which is nothing but a string containing a number to convert to double.

public static double ToDouble(string strValue, IFormatProvider provider);
Salin selepas log masuk

In the above syntax, ToDouble() method takes two arguments; the first is the string representation of a number which needs to be converted to double and second is an object which provides culture-specific formatting information. After conversion both these methods return the equivalent double value for the string passed as the argument.

How to Convert String to Double in C#?

In C#, the “System” namespace contains a class called “Convert” which contains the ToDouble() method in many overloaded forms to convert the specified type of data to its equivalent double value. Among these overloaded forms, two forms allow us to convert a string representation of a number to its equivalent double-precision floating-point number.

These two forms are as follows:

1. ToDouble(String);

Let us understand the working of the above method with the help of the below example:

double doubleVal = Convert.ToDouble("855.65");
Salin selepas log masuk

In the above statement, we have passed a number i.e. “855.65” as a string to ToDouble() method which will be converted to double by the method and the resulted value will be stored in a variable of type double (doubleVal).

2. ToDouble(String, IFormatProvider);

Let us now understand the working of the above method with the help of the below example:

NumberFormatInfo provider = new NumberFormatInfo();
provider.NumberDecimalSeparator = ".";
provider.NumberGroupSeparator = ",";
double doubleVal = Convert.ToDouble("855.65", provider);
Salin selepas log masuk

In the above statements, we first created an object of IFormatProvider using the class NumberFormatInfo which implements IFormatProvider. Then, we set some important properties for this object like NumberDecimalSeparator and NumberGroupSeparator.

  • NumberDecimalSeparator is used to get or set a string that can be used as the decimal separator in numeric values.
  • NumberGroupSeparator is used to get or set a string that separates groups of digits at the left of the decimal in numeric values.
  • Now, Convert.ToDouble() method will convert the given string to double using the formatting information provided by the object of NumberFormatInfo and the resultant value will be stored in the variable “doubleVal”.
  • If the value of the string in both of the above methods is “null” then these methods will return zero.
  • In C#, there exists another common way of converting a string to double which can be done by using Double.Parse() method and Double.TryParse() method.
  • Double.Parse(String) method works similarly to Convert.ToDouble() method as it takes a string representation of a number as an argument and converts it to a double-precision floating-point number. The difference is that if the string is “null” then this method does not return zero instead it returns ArgumentNullException.
  • Double.TryParse(String, Double) method works the same as Double.Parse() method except it returns a Boolean value which indicates whether the conversion has been done successfully or not. On success, it returns true and the respected double value gets stored in the ‘out’ parameter.

Examples of Convert String to Double in C#

Example showing the conversion of string to double using Convert.ToDouble() method.

Example #1

Code:

using System;
using System.Globalization;
namespace ConsoleApp4
{
public class Program
{
public static void Main(string[] args)
{
string[] strValues = {"85545.624", "34567.6790",
"5689.1234"};
double doubleVal = 0;
try
{
//creating an object of NumberFormatInfo
NumberFormatInfo provider = new NumberFormatInfo();
provider.NumberDecimalSeparator = ".";
provider.NumberGroupSeparator = ",";
Console.WriteLine("Equivalent double value of " +
"specified strings: ");
for (int i = 0; i < strValues.Length; i++)
{
//converting string to double
doubleVal = Convert.ToDouble(strValues[i], provider);
//displaying the converted double value
Console.WriteLine("{0}", doubleVal);
}
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
}
}
Salin selepas log masuk

Output:

Tukar String kepada Double dalam C#

Example #2

Example showing the conversion from string to double using Double.TryParse() method.

Code:

using System;
using System.Globalization;
namespace ConsoleApp4
{
public class Program
{
public static void Main(string[] args)
{
string[] strValues = {"2,6893.57", "$2,6893.57", "-2.948e6",
"-1.79769313486232E+308", "456BE6",
null, String.Empty, "JKLMN"};
Double doubleVal = 0;
Console.WriteLine("Equivalent double value of " +
"specified strings: ");
Console.WriteLine("\n");
for (int i = 0; i < strValues.Length; i++)
{
if (Double.TryParse(strValues[i], out doubleVal))
//displaying the converted double value
Console.WriteLine("'{0}' -> {1}", strValues[i], doubleVal);
else
Console.WriteLine("Not able to convert '{0}'", strValues[i]);
}
Console.ReadLine();
}
}
}
Salin selepas log masuk

Output:

Tukar String kepada Double dalam C#

Example #3

Example showing scenario when the string to be converted to double is either ‘null’ or empty.

Code:

using System;
using System.Globalization;
namespace ConsoleApp4
{
public class Program
{
public static void Main(string[] args)
{
string[] strValues = {null, String.Empty};
Double doubleVal = 0;
//creating an object of NumberFormatInfo
NumberFormatInfo provider = new NumberFormatInfo();
provider.NumberDecimalSeparator = ".";
provider.NumberGroupSeparator = ",";
Console.WriteLine("Result of conversion using " +
"Double.TryParse() method: ");
Console.WriteLine("\n");
for (int i = 0; i < strValues.Length; i++)
{
if (Double.TryParse(strValues[i], out doubleVal))
{
Console.WriteLine("'{0}' -> {1}", strValues[i], doubleVal);
}
else
{
Console.WriteLine("Not able to convert '{0}'", strValues[i]);
}
}
Console.WriteLine("Result of conversion using " +
"Convert.ToDouble() method: ");
Console.WriteLine("\n");
try
{
for (int i = 0; i < strValues.Length; i++)
{
doubleVal = Convert.ToDouble(strValues[i], provider);
Console.WriteLine("'{0}' -> {1}", strValues[i], doubleVal);
}
Console.ReadLine();
}
catch(Exception exception)
{
Console.WriteLine(exception.Message);
Console.ReadLine();
}
}
}
}
Salin selepas log masuk

Output:

Tukar String kepada Double dalam C#

Kesimpulan

  • Nilai rentetan boleh ditukar kepada dua kali ganda menggunakan kaedah Convert.ToDouble() atau Double.Parse().
  • Kaedah ini mengambil perwakilan rentetan nombor sebagai input dan mengembalikan nombor titik terapung berketepatan dua kali yang setara.
  • Kedua-dua kaedah ini mengembalikan FormatException jika hujah rentetan tidak mewakili nombor dalam format yang sah.

Atas ialah kandungan terperinci Tukar String kepada Double dalam C#. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Label berkaitan:
sumber:php
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!