How can I convert a number held by a string into a double?
The "safe" way:
string number = "9";
double result;
if(!double.TryParse(number, out result))
{
// conversion failed, string is not a valid double/number
}
or the "optimistic" way:
Convert.ToDouble(number);
Your safest bet is to use double.TryParse.
Use Double.TryParse()
Related
I need to extract a variable length decimal number from a string using c# and .NET. The input string is like $PTNTHPR,352.5,N,2.3,N,4.6,N,16*. I need the first occurrence of decimal number, i.e the 352.5 part. The numerical value ranges from 0.0 to 360.0 and I need that number from that string.
I searched a lot and got solution for a fixed length sub string but here I have variable length to extract. I have not tried with any code yet.
If it is always in this format you can use String.Split and decimal.Parse
var data = #"$PTNTHPR,352.5,N,2.3,N,4.6,N,16*";
var d = decimal.Parse(data.Split(new[]{','})[1]);
Console.WriteLine(d);
This is just a sample code to guide you. You should add additional exception handling logic to this, Also consider using decimal.TryParse
If you want to find the first occurance of decimal value you split the string and parse them one by one.
var data = #"$PTNTHPR,352.5,N,2.3,N,4.6,N,16*";
var splited = data.Split(new[]{','});
decimal? value = null;
foreach (var part in splited)
{
decimal parsed;
if (decimal.TryParse(part, out parsed))
{
value = parsed;
break;
}
}
Console.WriteLine(value);
First occurence in any of the tokens? Use String.Split to separate them and LINQ to find the first. You can use decimal.TryParse to check if it's parsable:
decimal? firstParsableToken = "$PTNTHPR,352.5,N,2.3,N,4.6,N,16*".Split(',')
.Select(s => s.TryGetDecimal(NumberFormatInfo.InvariantInfo))
.FirstOrDefault(d => d.HasValue);
Used this simple extension method to parse it to decimal?:
public static decimal? TryGetDecimal(this string item, IFormatProvider formatProvider = null, NumberStyles nStyles = NumberStyles.Any)
{
if (formatProvider == null) formatProvider = NumberFormatInfo.CurrentInfo;
decimal d = 0m;
bool success = decimal.TryParse(item, nStyles, formatProvider, out d);
if (success)
return d;
else
return null;
}
If the string is always comma separated, can you not use string.Split() to get each section, then use double.TryParse() to test if that part is numeric?
public static class Helper
{
public static string MyExtract(this string s)
{
return s.Split(',').First(str => Regex.IsMatch(str, #"[0-9.,]"));
}
}
Use it like this: string str = "$PTNTHPR,352.5,N,2.3,N,4.6,N,16*".MyExtract();
Then convert it to double/decimal if you need it.
Hello I retrieve data from webbrowser control by use getelementbyid.
var element = webbrowser.document.getelementbyid(something);
i have a problem is cant convert to double which can convert to string.
i want to know about convertion to be double. it's can possible?
i tried already but ...
Input string was not in a correct format.
What's wrong?
Use value of html element.
Try this,
double d = double.Parse(webbrowser.document.getelementbyid(something).value);
I assume you're trying to do something like this;
string innerHtml = webbrowser.Document.GetElementById(something).InnerHtml;
double value;
if(Double.TryParse(innerHtml, out value))
{
// value is now populated
};
You could use
double d;
string element = webbrowser.document.getelementbyid(something).Value;
if (Double.TryParse(element, out d))
{
// Conversion succesful: in d you find your number
}
Take a look at Double.TryParse syntax.
After retrieving the value in string form, you should use Double.TryParse to parse it as a double, e.g.:
double number;
if (Double.TryParse(webbrowser.document.getelementbyid(something), out number))
{
// ... do something useful with 'number' ...
}
I'm trying to convert this string to double
Convert.ToDouble("1.12");
and this is the output
System.FormatException was unhandled.
Should I do something like this?
public static double ConvertToDouble(string ParseVersion)
{
double NewestVersion;
try
{
NewestVersion = Convert.ToDouble(ParseVersion);
}
catch
{
ParseVersion = ParseVersion.Replace('.', ',');
NewestVersion = Convert.ToDouble(ParseVersion);
}
return NewestVersion;
}
ConvertToDouble("1.12");
Or is there an easier solution?
double.Parse will use the current culture by default. It sounds like you want the invariant culture:
double d = double.Parse("1.12", CultureInfo.InvariantCulture);
EDIT: Just to be clear, obviously you shouldn't use this if you're trying to parse text entered by a user in a different culture. This is for use when you've received data in the invariant culture (as most machine-to-machine data text-based formats are) and want to enforce that when parsing.
You don't have to replace . to ,.. however a better way is to use the .net TryParse method like:
double d;
if (double.TryParse("your string data", out d)
{
Console.WriteLine(d);
}
Edit: Also note that by replacing . by , you are getting a wrong results, for instance 1.12:
double d = double.Parse(1.12);//d will equals to 1.12
double d = double.Parse(1,12);//d will equals to 112.0
Convert.ToDouble uses Double.Parse internally. If you are unsure of the culture context, you should use an overload of Double.Parse precising the culture:
double d = double.Parse("1.12", CultureInfo.InvariantCulture);
Keep in mind, this problem can depend on where the input string comes from. If it is read from a database as an object, you might solve your problem by keeping it as an object and using Convert.ToDouble() as follows:
public double Double_fromObject(object obj)
{
double dNum = 0.0;
if (obj.ToString() != string.Empty) // the Convert fails when ""
{
try
{
dNum = Convert.ToDouble(obj);
}
catch (SystemException sex)
{
// this class's error string
LastError = sex.Message;
}
}
return (dNum);
}
I need to write a simple method that gets a string as an input, checks if it's a number and shows the number in it's original formatting.
For example:
Input: Output:
"123" 123
"-123" -123
"1.17" 1.17
"abd" ERROR
I was thinking about int.parse and double.parse but is there anyway to check if the string representation is an int or double?
Thanks!!
You can use Decimal.TryParse() then just display the string if it is a number, or error if it isn't.
int.TryParse() and double.TryParse() will do the job for you.
The result of the parsing operation is stored in an out parameter see http://www.dotnetperls.com/int-tryparse
The double tryparse method works the same...
TryParse will handle it.
http://msdn.microsoft.com/en-us/library/f02979c7.aspx
private static void TryToParse(string value)
{
int number;
bool result = Int32.TryParse(value, out number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
{
if (value == null) value = "";
Console.WriteLine("Attempted conversion of '{0}' failed.", value);
}
}
double result_double;
int result_int;
if (double.TryParse(your_string, out result_double))
Console.WriteLine(result_double);
else if (int.TryParse(your_string, out result_int))
Console.WriteLine(result_int);
else Console.WriteLine("error");
I would like to convert a string to double (very basic question isn't it ?)
string input = "45.00000";
double numberd = Double.Parse(input, CultureInfo.InvariantCulture);
=> my code works and I am very happy.
However I may have the following
string input = "";
double numberd = Double.Parse(input, CultureInfo.InvariantCulture);
In this case my code does not work and I get a Exception error ;(
I wonder how I can manage such situation. Ideally when I get this I would like to have my variable numberd equal to null.
Can anyone help me ?
Thx
Microsoft recommends using the Tester-Doer pattern as follows:
string input = "";
double numberd;
if( Double.TryParse(input, out numberd) )
{
// number parsed!
}
Use a Double for parsing, but a Double? for storing the value, perhaps?
Double number;
string input = ""; // just for demo purpose, naturally ;o)
Double? nullableNumber =
Double.TryParse(input, NumberStyles.Any, CultureInfo.InvariantCulture, out number)
? (Double?)number
: null;
// use nullableNumber
Primitive types like double cannot be null. You can have a nullable version with double? but, Double.Parse does not return a double? (just a plain double).
You could use Double.TryParse and check the return condition and set a double? to null accordingly if that would suit better.
Why not just catch the exception and set your variable?
double numberd;
try {
numberd = Double.Parse(input, CultureInfo.InvariantCulture);
} catch (System.FormatException e)
numberd = 0.0;
}
Alternatively, you can use Double.TryParse
Add an if statement comparing strings or surround with try/catch block.
Assuming you aren't worried about other invalid values besides empty strings, here's a simple one-liner:
Double? numberd = (input.Length == 0) ? null : (Double?)Double.Parse(input, CultureInfo.InvariantCulture);
mzabsky was on the right path, however his solution won't build and you shouldn't hard-code empty string - it's better to check the length of a string.
How about
Double? numberd = String.IsNullOrEmpty(str) ? null : Double.Parse(str)
In my application, I am parsing CSV files and I want these empty strings to be zero so I return 0.0 instead of null and it's all good.
5 more