I have a text box and I need to convert the value I entered.
and in the end i guess i need to convert Double into a data.
but there is something wrong
example code:
textbox1.Text = "24.5";
double data = int.Parse(textbox1.Text);
byte[] b = BitConverter.GetBytes((data)f);
int i = BitConverter.ToInt32(b, 0);
code working like this
byte[] b = BitConverter.GetBytes(22.3f);
int i = BitConverter.ToInt32(b, 0);
how can i insert string data ?
int.Parse() is wrong and will likely throw an exception. If you have the string value "24.5", what do you expect an integer to do with the ".5" portion?
Try this:
textbox1.Text = "24.5";
double data = double.Parse(textbox1.Text);
Even better if you use one of the double.TryParse() overloads.
I don't think you can write
byte[] b = BitConverter.GetBytes((data)f);
(data)f -> is not valid. I think you wanted to use it like 24.5f. Try to cast it into float. For example:
byte[] b = BitConverter.GetBytes((float) data);
Furthermore why would you parse a string as an int into a double? Parse the string directly as double.
Look at #Joel Coehoorn comment.
For more information about Double.TryParse() look at: Microsofts handbook about Double.TryParse
Related
I am trying to read some decimal values from my DB. These values are the order of 10-6. I am trying to read it into a double variable in C# using code like this: sqltype in database is "float". sample value to be read is "1.99999999495049E-06" –
Double [] rmseValues = null;
while (dataReader.Read())
{
// This shows my datatype is float (sql)
string temp = dataReader.GetDataTypeName(0);
// This returns a value of "0"
string temp1 = dataReader.GetOrdinal("RmseAll").ToString();
// This throws exception of invalid typecast
rmseValues[0] = dataReader.GetFloat(0);
}
Try to use GetDouble(0) instead of GetFloat(0)
I think you will also need to edit that line :
Double [] rmseValues = null;
In fact your are trying to put values inside a null object as solution you need to initialize your rmseValues array or just use a List of double
Double[] rmseValues = new Double[10];
Use GetInt64(0) instead of GetFloat(0)
In order not be dependent on RDBMS actual background type (say, NUMBER(10, 3) or alike) and its representation as .Net Type (e.g. Single) do a conversion:
// rmseValues[0] should be Double
rmseValues[0] = Convert.ToDouble(dataReader.GetValue(0));
i want to convert string to Byte[] in C# and with the help of previous topics i use this code :
string s = "0a";
System.Text.ASCIIEncoding encode = new System.Text.ASCIIEncoding();
byte[] b = encode.GetBytes(s);
Console.WriteLine(b);
but when i run this code it only prints : " System.byte[]"
I think I may have finally deciphered your question. Are you trying to get the hex digits of your string into an array?
I'm assuming that you want to take 2-digit hex values from a string and convert each lot into bytes. If not, I'm as lost as everyone else. Please note that I have not included any error checking!
byte[] data = new byte[s.Length/2];
for(int i = 0; i < s.Length/2; ++i)
{
byte val = byte.Parse(s.Substring(i*2,2), System.Globalization.NumberStyles.HexNumber);
data[i] = val;
}
foreach(byte bv in data)
{
Console.WriteLine(bv.ToString("X"));
}
If you want do this Console.WriteLine(b) it will prints the type of b which is System.Byte[].
In order to print the string stored in byte[] b, just make use of System.Text.ASCIIEncoding.GetString(byte[] b);
so in your case, encode.GetString(b); will get your string.
You can use BitConverter class Check: http://msdn.microsoft.com/en-us/library/3a733s97(v=vs.100).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
System.Text.ASCIIEncoding encode = new System.Text.ASCIIEncoding();
byte[] b = encode.GetBytes(s);
Console.WriteLine(BitConverter.ToString(b));
Your code already does the trick of converting string to byte, if your query is to print individual byte value, why not use a loop to print the value in byte array:
foreach (byte bb in b)
{
Console.Write(Convert.ToInt32(bb));
}
That's because it's returning the type of the object that you are typing. If you want to print the content of the array, try this:
Arrays.toString(byteArray)
I know this has some answers but not exactly what I'm looking for.
I have an application with a custom scripting language for file formats where numbers can be added, subtracted, etc...
One part will produce decimal,hex conversion and I was able to use the BigInteger class which is nice because I don't have to worry about large values.
For math operations though I am stuck using a Decimal and I would like to know if anyone has any suggestions for something like BigInteger that I can use for Decimal. I have seen BigRational but it doesn't look like it will fit.
Here is the code snippet where it's used. The asdecimal probably looks stupid but it's just decimal parse where zero is returned if invalid.
private string Subtract(StringReader reader, string text)
{
string value = reader.ReadToEnd();
value = Evaluate(value);
var a = text.AsDecimal();
var b = value.AsDecimal();
return (a - b).ToString();
}
To make this more clear. This function can handle any conceivable situation because of BigInteger
private string HexToDec(string value)
{
try
{
var input = this.Evaluate(value);
var number = BigInteger.Parse(input, System.Globalization.NumberStyles.HexNumber);
return number.ToString();
}
catch (Exception)
{
return "INVALID_HEX_NUMBER";
}
}
I would like subtract tot be as flexible. If it's not possible, that is fine.
This question already has answers here:
How to convert string to integer in C#
(12 answers)
Closed 8 years ago.
I need to convert a string to integer. My string can be of any type (float/int/string/special character).
For example:
If my string is "2.3", I need to convert to = 2
If my string is "anyCharacter", I need to convert to = 0
If my string is "2", I need to convert to = 2
I tried the following:
string a = "1.25";int b = Convert.ToInt32(a);
I got the error:
Input string was not in a correct format
How do I convert it?
Use Double.TryParse() and once you get the value from it, convert it to int using Convert.ToInt():
double parsedNum;
if (Double.TryParse(YourString, out parsedNum) {
newInt = Convert.ToInt32(num);
}
else {
newInt = 0;
}
Try to parse it as a floating point number, and convert to integer after that:
double num;
if (Double.TryParse(a, out num) {
b = (int)num;
} else {
b = 0;
}
This should help: treat any string as if it were a double, then Math.Floor() it to round it down to the nearest integer.
double theNum = 0;
string theString = "whatever"; // "2.3"; // "2";
if(double.TryParse(theString, out theNum) == false) theNum = 0;
//finally, cut the decimal part
int finalNum = (int)Math.Floor(theNum);
NOTE: the if might not be needed per-se, due to theNum initialization, but it's more readable this way.
I think Convert.ToInt32 is the wrong place to look for - I would use Integer.Tryparse and if TryParse evaluates to false, assign a 0 to the variable. Before the TryParse, you could simply delete any character after the dot, if you find it in the string.
Also, keep in mind that some languages use "," as a separator.
Try:
if (int.TryParse(string, out int)) {
variable = int.Parse(string);
}
As far as I know, there isn't any generic conversion, so you'd have to do a switch to find out the type of the variable and then use either of the following (for each type):
int.Parse(string)
or
int.TryParse(string, out int)
The second one will return a boolean which you can use to see if the conversion passed or failed.
Your best option would be to use double or decimal parsing as this won't remove any decimal places, unlike int.
bool Int32.TryParse(string, out int)
The boolean return value indicates if the conversion was successful or not.
Try something like this:
public int ForceToInt(string input)
{
int value; //Default is zero
int.TryParse(str, out value);
return value;
}
This will do the trick. However I don't recommend taking this approach. It is better to control your input whereever you get it.
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..