Novice enquiry on using TryParse() properly - c#

I've just tried TryParse, and am new to C# and just trying to understand everything, and then hopefully best practices...
Syntactically this works:
double number = Double.Parse(C.ReadLine());
Does TryParse only return a boolean, true if parse succeeds?
When I do this:
double number;
bool b = Double.TryParse(C.ReadLine(), out number);
number is the parsed input, from C.ReadLine(), as expected, everything works. Is this how TryParse is normally used? Trying to be efficient, appreciate advice like this.
Any advice on approach welcome, plus info on online resources for Try(things).

You use TryParse when it may fail, and you don't want your code to throw an exception.
For example
if (!Double.TryParse(someinput, out number))
{
Console.WriteLine("Please input a valid number");
}

Parse will return the double value if it succeeds and throws an exception otherwise. TryParse will return a boolean value representing the success of the operation and if it does succeed, it fills in the parsed value in the out argument you pass to it. It will never throw an exception.
In general, you should use TryParse when you expect the input string to not be a valid number and you have the logic to handle it (and display an error message, for instance).
If you don't expect the input string to be anything except a valid double you should use Parse.

The only differnce is that TryParse won't thow an exception if it can't parse the double.
This is handy when you want to assign a default value or ignore the value in your code
Example:
double number;
if (Double.TryParse(C.ReadLine(), out number))
{
// this is a double so all good
}
else
{
// not a valid double.
}
Example:
double number;
progressBar.Value = Double.TryParse(C.ReadLine(), out number) ? number : 4.0;
// If number is a valid double, set progressbar, esle set default value of 4.0
You also asked aboy TyrParse on Enum, this can be done like this
DayOfWeek fav;
if (Enum.TryParse<DayOfWeek>(Console.ReadLine(), out fav))
{
// parsed
}

Related

Cannot implicitly convert type 'string' to 'int' errors

I want to save the information entered in ASP.NET to the database and display it in GridView but the information that needs to be entered is dropdownlist selected.
The IDs of the elections held are kept.
int birim =Convert.ToInt32(DDLbirim.SelectedValue);
and
int birim=(int)DDLbirim.SelectedValue;
I write but in the form of an error. How can I help you track a way?
There are several ways to convert a string to int.
Convert.ToInt32 is one of them, but like int.Parse, it raises an exception if your string is not a numeric
To avoid the exception, you can use TryParse
The TryParse method is like the Parse or Convert.ToInt32 method, except the TryParse method does not throw an exception if the conversion fails.
bool isSuccees= Int32.TryParse(DDLbirim.SelectedValue, out birim );
I think your DDLbirim.SelectedValue is not a valid int so it can not cast it to a int hence the exception.
I would do an int.TryParse to check if the value is a valid int.
bool successfullyParsed = int.TryParse(DDLbirim.SelectedValue, out birim);
if (successfullyParsed){
// ...
}
The selectedValue is null when the dropdown isn't selected as valid. Else, as long as each item in the dropdown have a valid value, it will return as proper
The value is of type object, as it can store any type available.
Make sure that the values being set in the designer or backend are indeed integer and not string. Good way to identify would be as
if (ddlBrim.SelectedIndex >=0) {
var value = ddlBrim.SelectedValue;
// Inspect value in debugger to validate at this point
int intValue = -1;
if (Int32.TryParse(ddlBrim.SelectedValue, out intValue) {
// use the result value here
}
}
If DDLbirim.SelectedValue is null or if contains non-integer value you have to use TyrParse. TryParse handles nulls and invalid strings
int birim=0;
if (int.TryParse(DDLbirim.SelectedValue, out birim)){
}
Please make sure that you correctly bind the dropdownlist i.e. with displayMember, ValueMember (field must be parsable to the integer value), and Datasource.
Once it's fine, you can try to parse it.

Why does double.tryparse return false when parsing string input from console.ReadLine();

Newbie here, any help understanding is appreciated. First experience with tryparse.
In this instance:
do
{
Console.Write("What is the temperature (in degrees Fahrenheit): ");
outcome = double.TryParse(Console.ReadLine(), out tempf);
if (outcome == false)
{
Console.WriteLine("Invalid input");
}
} while (outcome == false);
A user input of 'stack' would return a boolean 'false' value, whereas an input such as '100' would return as 'true'.
I am under the impression that double.TryParse would only return true if the user input is of string type, as this would be a successful parse.
From msdn :
Double.TryParse Converts the string representation of a number to its double-precision
floating-point number equivalent. A return value indicates whether the
conversion succeeded or failed
So as long as conversion is possible it would return true. For example user input is "123X" will fail try parse.
You are using double.TryParse which means you are trying to parse inputed value to a double value. TryParse returns true if this can be done or it returns false.
As per your inputs, for user input of 'stack', TryParse is trying to parse it to a double value which is not a valid conversion and its failing and hence returning false. And for input such as '100', TryParse can do that perfectly.
Here is MSDN link for it

Convert.ToInt64 fails when value is "0.00000"

5 my code is like this
protected long Getvalue()
{
DataTable dt = GetDataBaseValue();
if (dt.Rows.Count > 0)
{
return Convert.ToInt64(dt.Rows[0]["BALANCE"].ToString());
}
return 0;
}
dt.Rows[0]["BALANCE"].ToString()=0.00000 I am getting the error here
PS: I tried to do this return long.Parse(...) and I got the same error
The problem is that "0.00000" is a String, which is an invalid format for "parsing to a long"1.
However, it may be sufficient to omit the ToString() conversion, and thus the above error, depending on what type the database actually returns. If the database returns an appropriate double/float/decimal then the following "Will Work", even if losing precision.
// Source is a double
Convert.ToInt64(0.0d) // -> 0
Convert.ToInt64(0.5d) // -> 0 (half-even rounding)
Convert.ToInt64(1.5d) // -> 2 (half-even rounding)
Convert.ToInt64(double.MaxValue) // -> OverflowException
// Source is a string
Convert.ToInt64("0") // -> 0
Convert.ToInt64("0.0") // -> FormatException: "not in a correct format"
If, for some uncorrectable reason, the database returns a String in the given format, it should suffice to first convert the string to a double/decimal (which do support such a format) and then to a long. Similar overflow and loss of precision cases are possible.
long v = (long)Convert.ToDecimal(dt.Rows[0]["BALANCE"]);
By default, .NET will parse integer values (e.g. int, long) from strings only when they conform to the pattern \s*[-+]?\d+\s* and will throw a FormatException otherwise; this is discussed in more detail in the linked documentation.
0.00000 is not a valid value for Int64. Perhaps you intended to use a Decimal (it looks like a currency amount) or otherwise truncate/round the value first?
Use Decimal.Parse("0.0000"); this is used for currency Not Long or Int64

How to Know whether Variable Contains a integers or Strings?

I just want to know, whether a variable contains a positive integer value.
Currently I am doing:
int APPOeeVersion =
Convert.ToInt32(ConfigurationManager.AppSettings["OEEVersion"]);
Here i just want to know whether APPOeeVersion Contains Int value or not. If not Need to show a error message as it is invalid format. Please help me out i have checked with several forums but not find exact solution.
Use int.TryParse, It will not raise an exception in case of failure and would give you bool value back if parsing was successful/unsuccessful.
string str = "1234";
int APPOeeVersion;
if (int.TryParse(str, out APPOeeVersion))
{
//parsing successful
}
else
{
//not an integer
}
If parsing is successful you will get the value of parsed string in your out parameter.
For checking a positive number and parsing you can have the check like:
if (int.TryParse(str, out APPOeeVersion) && APPOeeVersion > 0)
If you want to test for a positive integer, then you might need to use uint.TryParse since int.TryParse will allow negative values.
uint appoEeVersion;
var oeeVersionValue = ConfigurationManager.AppSettings["OEEVersion"];
if(!uint.TryParse(OEEVersionValue , out appoEeVersion))
{
// Error, not a positive integer
}
else
{
// Success, user value
}
int.TryParse would be the method: http://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx
int APPOeeVersion;
if(!int.TryParse(ConfigurationManager.AppSettings["OEEVersion"], out APPOeeVersion) || APPOeeVersion < 0){
//throw error
}
//use variable APPOeeVersion
I'm a little confused by your wording. Do you mean the variable is an integer or contains an integer?
If the former, then the solutions posted will work fine.
Are you guaranteed that the variable will only ever be an integer with no decimal notation (eg: 2 vs 2.0)? If not, you might need to use decimal.parse instead.
Integer parsing will fail on the other decimal values since they are not valid integers.
Decimal APPOeeVersion;
if (Decimal.TryParse(input,out APPOeeVersion))
{
Console.WriteLine("Successfully parse: {0} to {1}", input, APPOeeVersion);
}
else
{
Console.WriteLine("Failed to parse {0}", input);
}
Console.Write("\nEnter a number to test: ");
Then then use additional logic to ensure that the result is positive.
If you want to know whether it contains an integer, then a regular expression like the ones found here will work.
Maybe I'm just dumb or overthinking this, but it seems like you have to give a few more constraints

"Intelligent" cast of double to two differently formatted strings?

I'm working with a database that has the limit that the only (numeric) datatype it can store is a double. What I want to do is pick the number for a certain row and put it into an HTTP request. The problem revolves around that I cannot know if this number should or should not have decimals.
For example, if the double is an ID, I cannot have any kind of formatting whatsoever, since the site that gets the HTTP request will be confused. Observe the following examples:
site.com/showid.php?id=12300000 // OK
site.com/showid.php?id=1.23E7 // Bad; scientific notation
site.com/showid.php?id=12300000.0 // Bad; trailing decimal
The solution to this would be to cast it to a long. Ignoring the problem of overflowing the long, it solves the scientific notation and (obviously) trailing decimal. This could be an acceptable solution but it would be nice if the code didn't assume it were IDs we were dealing with. What if, for example, I were to query a site that shows a map and the number are coordinates, where the decimals are very important? Then a cast to long is no longer acceptable.
In short;
If the double has no decimals, do not add a trailing decimal.
If it has decimals, keep them all.
Neither case should have scientific notation or thousand separators.
This solution will be ported to both C# and Java so I accept answers in both languages.
(Oh, and I had no idea what to call this question, feel free to rename if you got something better.)
To complement the answer of gustafc (who beat me by 1 minute), here's the relevant code line for C#:
MyDouble.ToString("0.################")
or
string.Format("{0:0.################}", MyDouble);
Since it is safe to format the value with no trailing zeroes if it is integral (whether it represents an ID or a coordinate), why not just codify the logic you describe in your bullet points? For example (C#, but should translate readily to Java):
// Could also use Math.Floor, etc., to determine if it is integral
long integralPart = (long)doubleValue;
if ((double)integralPart == doubleValue)
{
// has no decimals: format it as an integer e.g. integralPart.ToString("D") in C#
}
else
{
// has decimals: keep them all e.g. doubleValue.ToString("F17")
}
How about encapsulating the number in a custom type?
public class IntelligentNumber
{
private readonly double number;
public IntelligentNumber(double number)
{
this.number = number;
}
public override string ToString()
{
long integralPart = (long)this.number;
if((double)integralPart == this.number)
{
return integralPart.ToString();
}
else
{
return this.number.ToString();
}
}
}
See also Vilx-'s answer for a better algorithm than the one above.
check whether num == round(num)
In Java, you can do this with DecimalFormat.
static String format(double n) {
return new DecimalFormat("0.###########################").format(n);
}
The # placeholders won't show up unless the number something other than zeros to put there, and the decimal point doesn't show up unless there's something following it.
Heres my own conclusion:
Check if the double has decimals.
Depending on that, format the string accordingly.
And then something important; without specifying an invariant culture, the comma in the has-decimals case may be a "," instead of a "." which isnt liked by HTTP requests. Of course, this problem only crops up if your OS is set to a locale that prefers the comma.
public static string DoubleToStringFormat(double dval)
{
long lval = (long)dval;
if ((double)lval == dval)
{
// has no decimals: format as integer
return dval.ToString("#.", CultureInfo.InvariantCulture);
}
else
{
// has decimals: keep them all
return dval.ToString("0.##################", CultureInfo.InvariantCulture);
}
}

Categories

Resources