Understanding Parse in C# - c#

Console.WriteLine("Enter a double number");
string numberInput = Console.ReadLine();
double number = Double.Parse(numberInput)
My question is what is the last line of code doing? Is it doing the same thing as ToDouble?

The very short answer is:
Converts a string value into a double. e.g.
"2.3"(String) will become 2.3(double).
You have many choices on how to do this:
Double.TryParse()
Convert.ToDouble()
Double.TryParse() is handy if you don't know 100% that the input string is going to be a number value.

It is converts a string to double, the Console.ReadLine() methods read a string data and store it on string variable named numberInput, to convert from that string to double, Double.Parse is called we passing to it the numberInput string and it will convert it to double.

"Converts the string representation of a number in a specified style to its double-precision floating-point number equivalent."
See MSDN.

It's taking String input and interpreting it as numeric input - Double in this case. String and Double are quite different types. For one, mathematical operations can be performed on Double.

Converts the string representation of a number to its double-precision floating-point number equivalent.
MSDN: http://msdn.microsoft.com/en-us/library/system.double.parse.aspx

It's calling the Double.Parse method. According to the MSDN page it
Converts the string representation of a number to its double-precision floating-point number equivalent.
As per #DoctorMick's answer: It does the same thing as the Convert.ToDouble method.
In this case it's used because the code is getting a string from the user which can be thought of as a sequence of letters. We would want to get this into the proper type that we want to work with, which in this case is Double. Double has the parse method for this.

The data read into the variable numberInput is a string. The last line parses this into the type System.Double, so that it is better typed for other operations.
There is no guarantee that numberInput contains a valid numeric value, in which case the Parse method will throw an exception that you can catch.

There have been 7 different answers yet everyone seems to have overlooked the question of is it doing the same as ToDouble. The short answer is yet, it is doing the same, in fact ToDouble calls double.Parse internally.

Related

Convert.ToInt32 behavior string vs float/double literal

Convert.ToInt32 behaves different when passed string vs float/double literal
var result = Convert.ToInt32(12.4);//returns 12
result = Convert.ToInt32(12.44);//returns 12
result = Convert.ToInt32(12.4444444);//returns 12
result = Convert.ToInt32("12.4"); // Input string was not in a correct format.
I understand different overloads of Convert.ToInt32 are being called for string and float/double
The question is why this inconsistent behavior shouldn't single overload for Convert.ToInt32 throw an exception for loss of precision ?
The question is why this inconsistent behavior shouldn't single
overload for Convert.ToInt32 throw an exception for loss of precision
?
You can think of the utility methods you're currently using to convert from double to int as "casting" i.e (int)12.4, (int)12.44 etc. which in essence means you for sure know that there is high chance that you'll lose data precision, thus in short is like telling the compiler "go ahead and convert it as I don't mind data loss", so, no exception will be thrown whereas the last example that converts from string to int should throw an exception because according to MSDN:
ToInt32(String) method is equivalent to passing value to the
Int32.Parse(String).
and as we all know Int32.Parse(String) throws an exception if the specified string is not in the correct format.
The way I see it, when you start with an float/double and you convert to int you expect a loss of precision. When you have a string that you convert to int you don't expect the parsing to do any losing of data, you just want it to parse and fail if the string is not valid.
You first have to convert your string into double, then cast it to int. or do another convert to int.
result = Convert.ToInt32(Convert.ToDouble("12.4"));
From msdn Convert.ToInt32(string)
Converts the specified string representation of a number to an equivalent 32-bit signed integer.
https://msdn.microsoft.com/en-us/library/sf1aw27b(v=vs.110).aspx
In given examples you can see that converting from double representation to int gives format exception.
so this is clearly by design. you should do it right.

How to parse a value obtained from NumericUpDown?

I have a NumericUpDown widget on my winform declared as numEnemyDefence. I want to use this to perform basic math on a variable:
damagePerHit -= Double.Parse(numEnemyDefence.Value);
Where damagePerHit is a double.
However, I am returned with the error of:
Cannot convert decimal to string.
Where is the string coming from? And why is the parse not working?
Double.Parse expects its argument to be a string. NumericUpDown.Value is a decimal. The C# compiler rejects your code because it doesn't make automatic conversions for you from the decimal type to the string type. And this is a good thing because it prevents a lot of subtle errors.
You can simply cast the decimal value to a double value
damagePerHit -= (double)numEnemyDefence.Value;
I also recommend to change (if possible) your variable damagePerHit to a simple decimal if you don't need the precision of a double value.
By the way these kind of operations are also source for other head scratching when you hit the floating point inaccuracy problem
Use Convert class and Convert.toDouble method

Convert long Double to Int?

Trying to convert the following value:
9.40551020088303E+21
to
9405510200883031584406
I am a but lost on how to do this? Math.Round, (int)Value.
Edit: Ok i may be wrong here, but i am trying to convert this to 9405510200883031584406 in anyway possible, it can be a string, or different type.
The final result is a tracking number and what i am starting with is what the shipping company provides me with.
the closest thing I can think of is using BigInteger
double d = 9.40551020088303E+21;
BigInteger bi = new BigInteger(d);
Console.WriteLine(bi.ToString());
Output would be:
9405510200883030261760
What you're describing isn't possible. An int (Int32) data type has a maximum value of 2147483647.
the long (Int64) data type, can only go up to 9,223,372,036,854,775,807
an unsigned long (UInt64) can go to 18,446,744,073,709,551,615
The number is simply too large for any of those data types.
9,405,510,200,883,031,584,406 (Your value)
9,223,372,036,854,775,807 (Int64.MaxValue)
18,446,744,073,709,551,615 (UInt64.MaxValue)
If you just want to convert this to a string as in your question it can be a string, or different type. Than this should suffice.
decimal value = 9405510200883031584406m;
string str = value.ToString("F0");
However, this assumes you know the actual full number. You can't convert 9.40551020088303E+21 to a more precise value, if you don't know the trailing digits.
You can see how to format in Standard Numeric Format Strings
The fixed-point ("F) format specifier converts a number to a string of
the form "-ddd.ddd…" where each "d" indicates a digit (0-9). The
string starts with a minus sign if the number is negative. The
precision specifier indicates the desired number of decimal places. If
the precision specifier is omitted, the current
NumberFormatInfo.NumberDecimalDigits property supplies the numeric
precision.

C# Comparing Decimal types as String

I am writing a logging system for our site and it looks at changes to Entities to see if they should be logged. I keep having a problem where the version of the Entity in the database shows decimal numbers (in string format) as "132.0000" and the current Entity has it as "132" with no decimal places.
Is there a way that I can force it to either remove the ".0000" from one or add it to the other?
Hm, simply parse the value from the database into a decimal and compare it to the decimal you already have?
You can try:
if(132 == Convert.ToDecimal("132.0000")
{
//Do Stuff
}
Replace 132 and "132.0000" with your appropriate values.
Also, if you wanted to remove the decimal portion of "132.0000", you can do:
string dec = "132.0000";
dec = dec.Substring(0,dec.IndexOf("."));
Convert the entry back to decimal, I'd say.
If you always want to remove the decimal, why not cast the object to an int and then make a string of it?
Provided all of the comparisons are numerics, you have to find the commonality between the two. In your post, you have already provided the answer. You need an integral number rather than a floating point number. Cast both strings to one of the integral types and compare.
You can use formatter string : F4
xxx.ToString("F4")

Difference between Convert.ToDecimal(string) & Decimal.Parse(string)

What is the difference in C# between Convert.ToDecimal(string) and Decimal.Parse(string)?
In what scenarios would you use one over the other?
What impact does it have on performance?
What other factors should I be taking into consideration when choosing between the two?
There is one important difference to keep in mind:
Convert.ToDecimal will return 0 if it is given a null string.
decimal.Parse will throw an ArgumentNullException if the string you want to parse is null.
From bytes.com:
The Convert class is designed to
convert a wide range of Types, so you
can convert more types to Decimal than
you can with Decimal.Parse, which can
only deal with String. On the other
hand Decimal.Parse allows you to
specify a NumberStyle.
Decimal and decimal are aliases and
are equal.
For Convert.ToDecimal(string),
Decimal.Parse is called internally.
Morten Wennevik [C# MVP]
Since Decimal.Parse is called internally by Convert.ToDecimal, if you have extreme performance requirements you might want to stick to Decimal.Parse, it will save a stack frame.
One factor that you might not have thought of is the Decimal.TryParse method. Both Convert.ToDecimal and Parse throw exceptions if they cannot convert the string to the proper decimal format. The TryParse method gives you a nice pattern for input validation.
decimal result;
if (decimal.TryParse("5.0", out result))
; // you have a valid decimal to do as you please, no exception.
else
; // uh-oh. error message time!
This pattern is very incredibly awesome for error-checking user input.
One common suggestion related to original topic - please use TryParse() as soon as you not really sure that input string parameter WILL be correct number format representation.
Major Difference between Convert.ToDecimal(string) and Decimal.Parse(string)
is that Convert handles Null whereas the other throws an exception
Note: It won't handle empty string.
Convert.ToDecimal apparently does not always return 0. In my linq statement
var query = from c in dc.DataContext.vw_WebOrders
select new CisStoreData()
{
Discount = Convert.ToDecimal(c.Discount)
};
Discount is still null after converting from a Decimal? that is null. However, outside a Linq statement, I do get a 0 for the same conversion. Frustrating and annoying.
Knowing that Convert.ToDecimal is the way to go in most cases because it handles NULL, it, however, does not handle empty string very well. So, the following function might help:
'object should be a string or a number
Function ConvertStringToDecimal(ByVal ValueToConvertToDecimal As Object) As Decimal
If String.IsNullOrEmpty(ValueToConvertToDecimal.ToString) = False Then
Return Convert.ToDecimal(ValueToConvertToDecimal)
Else
Return Convert.ToDecimal(0)
End If
End Function

Categories

Resources