在C#中将字符串转换为double

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11399439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:43:40  来源:igfitidea点击:

Converting string to double in C#

c#stringdoubletype-conversion

提问by whoah

I have a long string with double-type values separated by #-value1#value2#value3#etc

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

I splitted it to string table. Then, I want to convert every single element from this table to double type and I get an error. What is wrong with type-conversion here?

我将它拆分为字符串表。然后,我想将此表中的每个元素都转换为双精度类型,但出现错误。这里的类型转换有什么问题?

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
}

采纳答案by Zbigniew

There are 3 problems.

有3个问题。

1) Incorrect decimal separator

1) 小数点分隔符不正确

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:

您可以使用重载方法解析双打,该方法将文化作为第二个参数。在这种情况下,您可以使用InvariantCulture什么是不变文化),例如使用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.

您还应该看看double.TryParse,您可以将它与许多选项一起使用,并且检查您的字符串是否有效特别有用double

2) You have an incorrect double

2)你的双打不正确

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

您的值之一不正确,因为它包含两个点:

15.5859949000000662452.23862099999999

15.5859949000000662452.23862099999999

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

3) 你的数组最后有一个空值,这是一个不正确的双精度

You can use overloaded Splitwhich removes empty values:

您可以使用重载Split来删除空值:

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

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

回答by Rob I

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

在您的字符串中,我看到:15.5859949000000662452.23862099999999这不是双精度数(它有两个小数点)。也许这只是一个合法的输入错误?

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

您可能还想弄清楚您的最后一个String是否为空,并说明这种情况。

回答by Ervi B

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.aspxhas a really good example on how to use them.

这个http://msdn.microsoft.com/en-us/library/system.double.tryparse.aspx有一个关于如何使用它们的很好的例子。

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

如果您需要很长的 Int64.TryParse,也可以使用:http: //msdn.microsoft.com/en-us/library/system.int64.tryparse.aspx

Hope that helps.

希望有帮助。

回答by bask0xff

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);

回答by Arun Prasad E S

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

添加一个类为 Public 并像 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());

回答by Asiamah Amos

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

你可以试试这个例子。一个简单的 C# 程序将字符串转换为双精度

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());

   }
}