tags:

views:

648

answers:

4

How can I get the double value from a textbox in .NET using C++. Do I have to get the text and do an atof() or is there an easier way?

+3  A: 

Yes, you have to get the text and parse it - although you could stick within .NET and use Double.TryParse instead of atof(), which lets you detect user error more easily.

Convert.ToDouble and Double.Parse would both throw exceptions in the case of failure; atof() will silently ignore bad input from what I remember. Double.TryParse just returns true/false to indicate success/failure, and uses an out parameter to pass back the result of the parse. This is usually the right thing to do for user input - you want to be able to detect the failure, but exceptions aren't really appropriate as users entering invalid data is a far from exceptional situation.

Jon Skeet
A: 

In .NET you can use Double.Parse, Double.TryParse, or Convert.ToDouble.

Jakob Christensen
+1  A: 

You have to parse the text.

Double value = 0.0;

if (Double.TryParse(textBox.Text, out value))
{
    // Value is valid here.
}
else
{
   // Handle invalid input here.
}
Daniel Brückner
If you're going to throw a FormatException on failure you might as well just use Double.Parse() :) (You should also be passing in "value" as an out parameter, which means you don't need to initialize it to start with.)
Jon Skeet
I just typed to quick and forgott out value - there is no single parameter overload at all. The exception was just meant as example, but you are right, a bad example. And I prefer to explictly initialize variables.
Daniel Brückner
If you explicitly initialize a variable when that value can never be used, surely that's misleading isn't it? When it's immediately used as an out parameter, whatever value you put in is guaranteed to be overwritten unless an exception is thrown. Why pretend that the previous value was important?
Jon Skeet
I don't know if this is the case in the CLR/C#, but there are good reasons to always initialize FP values http://blogs.msdn.com/oldnewthing/archive/2008/07/02/8679191.aspx
Logan Capaldo
A: 

it gives me an error when I try to use Double.TryParse, what do I need to include for this. sorry usually use linux.

danbruc has edited his example so now it is correct. What error are you getting?
Jakob Christensen
The double.tryparse worked, I don't have the ablitiy to use Convert.ToDouble or Convert.anything do you know why?