C# object and string conversion - c#

I have following section of code in my program:
object val;
val = arr[1].Trim(); // in my case i am getting value here is 1.00
now when I am assigning value to a datarow I am getting error
Expected int64 value.
datarow[Convert.ToString(drow["col"]).Trim().ToUpper()] = val;
I am not facing any issue when getting value other that 1.00.
What could be the exact problem? How can I solve it?
Suggestions and solutions are welcome

If that column in your datatable is expecting an Int64 you need to convert val (which is a string) to an Int64:
var val = arr[1].Trim(); // String at this point
long longVal = 0;
if(!long.TryParse(val,out longVal){
throw new InvalidOperationException("value wasnt an Int64!");
}
datarow[Convert.ToString(drow["col"]).Trim().ToUpper()] = longVal

arr[1] seems to be string, and applying .Trim() keeps it as a string, even if it's "1.00". If you need an integer, you need to parse it. However, it can't be parsed to an intteger, because it's actually a double.
As a proof of whether I'm right or not, you can try (Int64)double.Parse(val) and that should work. However, it's up to you to decide whether that's not an issue for your program. There's two possible issues:
val might not be parse-able to double, in which case you will get an exception
val might be a double, but not one that can be represented as an int (too large, or lose precision ex. "1.8" would become 1)
Hope this helps

Related

How to transform a different notation floating point number to double?

I'm currently trying to convert a few numbers from a DB2 Server into double values in C#.
The getting of the data from the DB2 Server is not a Problem, and I get the data into a DataTable quite easily. The Problem then Comes when I try to convert the objects into double values, as the Notation is different (, instead of . as example).
Thus the code:
foreach (DataRow row in DataTable myResultTable)
{
double myValue = String.IsNullOrEmpty(row["myValue"].ToString())? 0 : (double)row["myValue"]; // myValue has 1234,56 as Content.
}
Fails with an exception that the value can't be converted.
The datatype of the field myValue in the db2 is Decimal with a length of 16.
As I didn't find anything, I thought about converting it to string, formating it there and then transform that into a double but that seems quite....complicated to me for something that should be easy (and complicated always means prone to Errors because of something unexpected).
So my question is: Is there any easy way to do this Transformation?
Edit:
As it was asked a GetType on row["myValue"] results in: {Name = "Decimal" FullName = "System.Decimal"}.
The real solution is to cast to decimal not to double:
var value = row["myValue"] is DBNull ? 0m : (decimal)row["myValue"];

double TryParse confusion

So I was dinking around in LinqPad and noticed something odd, I get same result in Visual Studio testing code Unit Tests.
I was playing with all the different TryParse for the numerical datatypes. During this I noticed that double.TryParse is acting a bit different then the rest.
For example:
var doubleStr = double.MinValue.ToString();
//doubleStr = -1.79769313486232E+308
double result;
var result = double.TryParse(doubleStr, out result);
//result is returning false
All other datatypes with the MinValue are not having this trouble:
var floatStr = float.MinValue.ToString();
//floatStr = -3.402823E+38
float result2;
float.TryParse(floatStr, out result2);
//result = True
Any body know why double is the only one that false to parse the string version of it's MinValue property back to an actual double?
I am not seeing why this is different off hand. Maybe I am missing something.
To get a string that can be surely re-parsed as a double, use the "R" (round-trip) format string:
double.Parse(double.MinValue.ToString("R"))
In other formats, the string you get may generally re-parse to a different value, due to rounding. With double.MinValue, this gets especially worse, since the different value it would re-parse to is outside of the range of double. Hence the parse failing.

convert variable in asp.net

I wrote a piece of simple code that I dont to find what the problem.
the code is:
var sortSecurities="SELECT * FROM securities";
int total=0;
var value="";
foreach(var row in db.Query(sortSecurities))
{
value=row.lastGate;
total=Convert.ToInt32(value)*100;// here the problem with compilation..
db.Execute("INSERT INTO holding(IDgrossPortfolio,IDSecurity,totalHolding,units,buyGate) "+"VALUES (#0,#1,#2,#3,#4)",row.category,row.number,total,"100",row.lastGate);
}
what the problem with the convert?
the error is:
Exception Details: System.FormatException: Input string was not in a correct format.
value does not hold a value that can be converted to Int32. If you could do some debugging and see what the value of it is from row.lastGate, you might see what the problem is.
Also, not sure what is returned by db.Query(sortSecurities) (or really what kind of object row.lastGate is), but you can also try to change value=row.lastGate; to value=row.lastGate.ToString();
you can use try parse to check if the value actually contains a number
int total;
bool result = Int32.TryParse(value, out total);
if (result)
{
db.Execute("INSERT INTO holding(IDgrossPortfolio,IDSecurity,totalHolding,units,buyGate) "+"VALUES (#0,#1,#2,#3,#4)",row.category,row.number,total,"100",row.lastGate);
}
Your value isn't successfully being parsed by Convert.ToInt32()
Alternatively, consider using Int32.TryParse() and validate if the data is indeed the type of data you're expecting.
int result;
if(Int32.TryParse(row.lastGate, out result))
{
//row.lastGate was a valid int
total = result * 100;
}
else
{
//row.lastGate wasn't a valid int
}
Thanks you for all... I try now and found elegant answer.
Like I wrote in the comments, becouse I know that the value of row.lastGate
represent a number I don't need to check it.
So I try this and it works:
var sortSecurities="SELECT * FROM securities";
int total=0;
double value=0;
foreach(var row in db.Query(sortSecurities))
{
value=Convert.ToDouble(row.lastGate);
total=Convert.ToInt32(value)*100;//100 is default
db.Execute("INSERT INTO holding(IDgrossPortfolio,IDSecurity,totalHolding,units,buyGate) "+"VALUES (#0,#1,#2,#3,#4)",row.category,row.number,total,"100",row.lastGate);
}
Probably I needed to change the value first of all to double and then to int
Becouse when I try to change it directly to int the Compiler did'nt interpret the
string right, becouse of the dot in the number (type double).
thanks about the the intention..

How to convert string into integer in WindowsPhone7

I need to convert a string to an integer in windows Phone 7. I tried following code but my app crashed:
int val1 = Convert.ToInt16(str);
Is there another way to do this?
Why does it crash? Do you get an errormessage? What is the actual value of 'str'? Maybe the problem lies there. Also I would opt for ToInt32() as this returns an int, while ToInt16() returns a short. This will not give a problem but it looks more logic. And last, these methods will do the job:
int val1 = Convert.ToInt32("123");
int val2 = int.Parse("123");
int val3 = 0;
int.TryParse("123", out val3);
To convert string to integer, use
string text = "500";
int num = int.Parse(text);
Have you tried
string str = "155";
int retVal;
if(int.TryParse(str, out retVal))
{
// You can now code with it
}
try Convert.ToInt32(str)
Think this will help :)
I think int.TryParse is the way to go. This way you will get to know if the parsing was successful or not by checking the return value. The advantage is since it does not throw any exception you don't have to write any error handling code which makes it simpler and less error prone. I do not personally like code that throws a lot of exceptions as one might easily goof up whilst handling them.
If you are sure to use this on a 32 bit platform, you can try Int32.TryParse() , or if 64- bit platform you may use Int64.TryParse()

Conversion vb6 to c#

I am trying to convert some vb6 code to c# and I am struggling a bit.
I have looked at this page below and others similar, but am still stumped.
Why use hex?
vb6 code below:
Dim Cal As String
Cal = vbNull
For i = 1 To 8
Cal = Cal + Hex(Xor1 Xor Xor2)
Next i
This is my c# code - it still has some errors.
string Cal = null;
int Xor1 = 0;
int Xor2 = 0;
for (i = 1; i <= 8; i++)
{
Cal = Cal + Convert.Hex(Xor1 ^ Xor2);
}
The errors are:
Cal = Cal + Convert.Hex(Xor1 ^ Xor2 ^ 6);
Any advice as to why I cant get the hex to convert would be appreciated.
I suspect its my lack of understanding the .Hex on line 3 above and the "&H" on line 1/2 above.
Note: This answer was written at a point where the lines Xor1 = CDec("&H" + Mid(SN1, i, 1))
and Xor1 = Convert.ToDecimal("&H" + SN1.Substring(i, 1)); were still present in the question.
What's the &H?
In Visual Basic (old VB6 and also VB.NET), hexadecimal constants can be used by prefixing them with &H. E.g., myValue = &H20 would assign the value 32 to the variable myValue. Due to this convention, the conversion functions of VB6 also accepted this notation. For example, CInt("20") returned the integer 20, and CInt("&H20") returned the integer 32.
Your code example uses CDec to convert the value to the data type Decimal (actually, to the Decimal subtype of Variant) and then assigns the result to an integer, causing an implicit conversion. This is actually not necessary, using CInt would be correct. Apparently, the VB6 code was written by someone who did not understand that (a) the Decimal data type and (b) representing a number in decimal notation are two completely different things.
So, how do I convert between strings in hexadecimal notation and number data types in C#?
To convert a hexadecimal string into a number use
int number = Convert.ToInt32(hex, 16); // use this instead of Convert.ToDecimal
In C#, there's no need to pad the value with "&H" in the beginning. The second parameter,16, tells the conversion function that the value is in base 16 (i.e., hexadecimal).
On the other hand, to convert a number into its hex representation, use
string hex = number.ToString("X"); // use this instead of Convert.ToHex
What you are using, Convert.ToDecimal, does something completely different: It converts a value into the decimal data type, which is a special data type used for floating-point numbers with decimal precision. That's not what you need. Your other method, Convert.Hex simply does not exist.

Categories