c# - 在 C# 中使用 Double.TryParse 方法转换字符串

标签 c# string double

现在,我将所有 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);

最佳答案

double heightVal = 0;
double.TryParse(_height, out heightVal); 

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

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

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

Output:

defaultValue = 0

success = false

成功范例:

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

Output:

defaultValue = 123

success = true

关于c# - 在 C# 中使用 Double.TryParse 方法转换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55521149/

相关文章:

c# - 注入(inject) UserManager 和 UserStore

php - java.lang.String类型的值<br的错误无法转换为JSONObject

floating-point - 两个不相等的 float 相减是否可以得到0?

android - 将 String 转换为 Double 时无效的 double

java - int 可以增加一个 double 值

c# - 在 C# 中 XML 反序列化后如何重建对象层次结构/引用

c# - 线程池最大线程数

c# - 如何使用 VS2010 安装项目将我的程序添加到用户开始菜单?

c# - 删除字符串的最后一个字符

python - 如何确定周期序列的最小周期