将公共类字符串转换为主类中的double

时间:2018-12-11 19:34:54

标签: c#

我正在尝试将在类中创建的字符串转换为双精度,以便可以在算术中使用它,但是遇到错误时,我尝试了以下操作:

/* Calling class to use number for conversion
      double LocalCentToInch = Convert.ToDouble(CentI);
      double YourAnswer = MyConvert * LocalCentToInch;
      */
      //Ignore these lines just testing type converison and failing
      //Console.WriteLine(CentI);
      //Console.WriteLine(CentI.ToDouble());
      double LocalCentToInch;
      LocalCentToInch = Convert.ToInt32(CentI);
      Console.WriteLine(LocalCentToInch);

我正在从名为convert one的类进行调用,它看起来像这样:

/////////////////////centimetres to inches///////////////////////////////
public class ConvertOne 
{
  public ConvertOne()
  {
    Centtoinch = "0.3937008";
  }

  public ConvertOne(string centtoinch)
  {                                   //make new string with var data
    Centtoinch = centtoinch;
  }

  public string Centtoinch   { get; }


  public override string ToString()
  {
    return Centtoinch;
  }


}
///////////////////////end of centimetres to inches////////////////////////////

主要方法是数学下降的地方,当前看起来像这样:

  double YourAnswer = MyConvert * 0.3937008;
  Console.WriteLine("\nYour answer is:");
  Console.WriteLine(YourAnswer);

虽然我不想使用0.39377008,但我想从其类中调用此字符串并将其转换为双精度,以便可以在“ YourAnswer”部分中使用。

如您所见,尽管我不确定下一步该怎么做,但是我尝试了不同的方法。

我得到的错误是:

Unhandled Exception:
System.InvalidCastException: Specified cast is not valid.
  at System.Convert.ToInt32 (System.Object value) [0x00003] in <71d8ad678db34313b7f718a414dfcb25>:0 
  at testConverter.Main () [0x000dc] in <93d359b0b3204d6482ac66dd3e4b0858>:0 
[ERROR] FATAL UNHANDLED EXCEPTION: System.InvalidCastException: Specified cast is not valid.
  at System.Convert.ToInt32 (System.Object value) [0x00003] in <71d8ad678db34313b7f718a414dfcb25>:0 
  at testConverter.Main () [0x000dc] in <93d359b0b3204d6482ac66dd3e4b0858>:0 
exit status 1

1 个答案:

答案 0 :(得分:0)

这是将字符串转换为双精度字符的方法

var str = "1.23";
var dble = Convert.ToDouble(str);

var str = "1.23";
var dble = Double.Parse(str);

实际上Convert.ToDouble,简单地调用第二种方法-参见https://referencesource.microsoft.com/#mscorlib/system/convert.cs,d98fcd7819f63d0f