使用C#中的Double.TryParse方法转换字符串

问题描述 投票:1回答:2

现在,我将所有3个字符串转换为int,但是我无法使用Double.TryParse方法转换每个字符串。我想使用该方法而不是int。

我尝试使用这种类型的代码if(Double.TryParse(value,out number)),但我不确定这是否正确。

//Ask the user for height
Console.Write("Please enter the first part of your height in feet:");
string _height = Console.ReadLine();
int _heightVal = Int32.Parse(_height);

//Ask the user for inches
Console.Write("Please enter the second part of your height in inches:");
string _inches = Console.ReadLine();
int _inchesVal = Int32.Parse(_inches);

//Ask the user for pounds
Console.Write("Please enter your weight in pounds:");
string _pounds = Console.ReadLine();
int _poundsVal = Int32.Parse(_pounds);
c# string double
2个回答
3
投票
double heightVal = 0;
double.TryParse(_height, out heightVal); 

如果解析成功,heightVal将具有来自_height的Parse的值,否则它将具有它的先前值(此处为0)

TryParse()返回一个布尔值,指示解析是否成功,您可以像以下一样使用它:

bool success = double.TryParse(_height, out heightVal); 

要么

if(double.TryParse(_height, out heightVal))
{
     //Parse was successful and heightVal contains the new value
     // and you can use it in here
}

失败示例:

double defaultValue = 0;
string str = "abc"
bool success = double.TryParse(str, defaultValue );

输出:

defaultValue = 0

成功=错误

成功案例:

double defaultValue = 0;
string str = "123"
bool success = double.TryParse(str, defaultValue );

输出:

defaultValue = 123

成功=真


0
投票

我认为你只是试图强制使用输入正确的值,你可以像这样使用wile循环

 double userHeight = 0.0;
        while (true)
        { 
            //Ask the user for height
            Console.Write("Please enter the first part of your height in feet:");
            string _height = Console.ReadLine();
            if (Double.TryParse(_height, out double height))
            {
                userHeight = height;
                break;
            }

        }

然后适用于你的所有问题

© www.soinside.com 2019 - 2024. All rights reserved.