在 C # 中将 string 转换为 double

我有一个由 #-value1#value2#value3#等分隔的双类型值的长字符串

我把它分成了线桌。然后,我想把这个表中的每个元素都转换为 double 类型,结果得到一个错误。这里的类型转换有什么问题吗?

string a = "52.8725945#18.69872650000002#50.9028073#14.971600200000012#51.260062#15.5859949000000662452.23862099999999#19.372202799999250800000045#51.7808372#19.474096499999973#";
string[] someArray = a.Split(new char[] { '#' });
for (int i = 0; i < someArray.Length; i++)
{
Console.WriteLine(someArray[i]); // correct value
Convert.ToDouble(someArray[i]); // error
}
519213 次浏览

In your string I see: 15.5859949000000662452.23862099999999 which is not a double (it has two decimal points). Perhaps it's just a legitimate input error?

You may also want to figure out if your last String will be empty, and account for that situation.

There are 3 problems.

1) Incorrect decimal separator

Different cultures use different decimal separators (namely , and .).

If you replace . with , it should work as expected:

Console.WriteLine(Convert.ToDouble("52,8725945"));

You can parse your doubles using overloaded method which takes culture as a second parameter. In this case you can use InvariantCulture (What is the invariant culture) e.g. using double.Parse:

double.Parse("52.8725945", System.Globalization.CultureInfo.InvariantCulture);

You should also take a look at double.TryParse, you can use it with many options and it is especially useful to check wheter or not your string is a valid double.

2) You have an incorrect double

One of your values is incorrect, because it contains two dots:

15.5859949000000662452.23862099999999

3) Your array has an empty value at the end, which is an incorrect double

You can use overloaded Split which removes empty values:

string[] someArray = a.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);

Most people already tried to answer your questions.
If you are still debugging, have you thought about using:

Double.TryParse(String, Double);

This will help you in determining what is wrong in each of the string first before you do the actual parsing.
If you have a culture-related problem, you might consider using:

Double.TryParse(String, NumberStyles, IFormatProvider, Double);

This http://msdn.microsoft.com/en-us/library/system.double.tryparse.aspx has a really good example on how to use them.

If you need a long, Int64.TryParse is also available: http://msdn.microsoft.com/en-us/library/system.int64.tryparse.aspx

Hope that helps.

private double ConvertToDouble(string s)
{
char systemSeparator = Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator[0];
double result = 0;
try
{
if (s != null)
if (!s.Contains(","))
result = double.Parse(s, CultureInfo.InvariantCulture);
else
result = Convert.ToDouble(s.Replace(".", systemSeparator.ToString()).Replace(",", systemSeparator.ToString()));
}
catch (Exception e)
{
try
{
result = Convert.ToDouble(s);
}
catch
{
try
{
result = Convert.ToDouble(s.Replace(",", ";").Replace(".", ",").Replace(";", "."));
}
catch {
throw new Exception("Wrong string-to-double format");
}
}
}
return result;
}

and successfully passed tests are:

        Debug.Assert(ConvertToDouble("1.000.007") == 1000007.00);
Debug.Assert(ConvertToDouble("1.000.007,00") == 1000007.00);
Debug.Assert(ConvertToDouble("1.000,07") == 1000.07);
Debug.Assert(ConvertToDouble("1,000,007") == 1000007.00);
Debug.Assert(ConvertToDouble("1,000,000.07") == 1000000.07);
Debug.Assert(ConvertToDouble("1,007") == 1.007);
Debug.Assert(ConvertToDouble("1.07") == 1.07);
Debug.Assert(ConvertToDouble("1.007") == 1007.00);
Debug.Assert(ConvertToDouble("1.000.007E-08") == 0.07);
Debug.Assert(ConvertToDouble("1,000,007E-08") == 0.07);

Add a class as Public and use it very easily like convertToInt32()

  using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


/// <summary>
/// Summary description for Common
/// </summary>
public static class Common
{
public static double ConvertToDouble(string Value) {
if (Value == null) {
return 0;
}
else {
double OutVal;
double.TryParse(Value, out OutVal);


if (double.IsNaN(OutVal) || double.IsInfinity(OutVal)) {
return 0;
}
return OutVal;
}
}
}

Then Call The Function

double DirectExpense =  Common.ConvertToDouble(dr["DrAmount"].ToString());

You can try this example out. A simple C# progaram to convert string to double

class Calculations{


protected double length;
protected double height;
protected double width;


public void get_data(){


this.length = Convert.ToDouble(Console.ReadLine());
this.width  = Convert.ToDouble(Console.ReadLine());
this.height = Convert.ToDouble(Console.ReadLine());


}
}