输入字符串的格式不正确。将String转换为double

时间:2010-03-13 22:47:58

标签: c# string

我是C#的初学者,可以在button1_click事件下执行空字符串到双重转换..但是在Public Form1()下执行它会给我这个错误

  

输入字符串不正确   格式。

这是代码..(form1.cs和Guy.cs类)

 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Drawing;
 using System.Linq;
 using System.Text;
 using System.Windows.Forms;

 namespace WindowsFormsApplication1
 {
     public partial class Form1 : Form
     {
        public Form1()
        {
            InitializeComponent();

            guy1 = new Guy() ;
            guy1.guyname = textBox1.Text;                
            guy1.guycash = double.Parse(textBox2.Text);
        }                 

    }

    Guy guy1 ;

    private void button1_Click(object sender, EventArgs e)
    {

        label5.Text = guy1.TakeCash(double.Parse(textBox3.Text)).ToString();

    }
 }


}

Guy.cs代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    class Guy
    {
        private string name;
        private double cash;

        public string guyname
        {
            get { return name; }
            set { name = value; }
        }

        public double guycash
        {
            get { return cash ; }
            set { cash = value; }
        }



        public double TakeCash(double amount)
        {
            if (cash > amount)
            {
                cash -= amount;
                return cash;
            }
            else
            {
                MessageBox.Show("Not enough Cash.");
                return 0;
            }
        }


    }
}

错误是由guy1.guycash = double.Parse(textBox2.Text);行引起的,当我在之前的If()中尝试double.TryParse(textbox2.Text, out x)时,它返回false。

请问这个怎么解决? 提前谢谢。

3 个答案:

答案 0 :(得分:4)

继续由旁观者回答:

double d;
if(!Double.TryParse(textBox2.Text, out d)){
    return; // or alert, or whatever.
}

guy1 = new Guy() ;
guy1.guyname = textBox1.Text;                
guy1.guycash = d;

您正在做的是尝试解析,如果失败,请采取其他措施。由于用户可以输入他们想要的任何内容,这可以保证如果您无法解析输入(因为它不是小数),您可以很好地处理它并告诉他们修复输入。

答案 1 :(得分:2)

这应该没问题

double d;
Double.TryParse(String.Empty, out d);

Double.TryParse Method (String, Double%)

答案 2 :(得分:1)

看起来问题是您没有处理不正确的用户输入。您正在尝试将字符串从文本框解析为双精度而不建议它可能无法正确解析(例如,用户可以在文本框中输入'abcd')。您的代码应使用TryParse方法,并在未解析输入时显示错误消息。

我认为解析失败是因为非数字输入或因为文化问题(比如你用“。”作为带有“,”的用户输入数字的简单符号)。

相关问题