I have the following code:
int a = 50;
float b = 50.60f;
a = int.Parse(b.ToString());
On run time this parsing gives as error. Why it is please guide me.
Thanks
It's trying to parse the string "50.6" - that can't be parsed as an integer, because 50.6 isn't an integer. From the documentation:
The s parameter contains a number of the form:
[ws][sign]digits[ws]
Perhaps you want to parse it back as a float and then cast to an integer?
a = (int) float.Parse(b.ToString());
This is because int.Parse throws NumberFormatException if the string does not contain a parsable integer; 50.6 is not a prasable integer.
You are trying to parse a string that does not represent an integer into an integer.
This is why you are getting an exception.
It gives an error because you are trying to parse as int a string representing a float.
float b = 50.60f; // b = 50.6
// b.ToString() = "50.6" or "50,6" depending on locale
// int.Parse("50.6") MUST give an error because "50.6" is
// not a string representation of an integer
What is it that you want to do? Convert a float to an int? Just do this:
float b = 50.6f;
int a = (int)b;
That will truncate the value of b to simply 50.
Or do you want it rounded off to the nearest integer?
int a = (int)Math.Round(b);
Is the error message not specific enough?
Input string was not in a correct format.
int.Parse must take a string which can be parsed to an integer. The string "50.6" does not fulfil that requirement!
Related
I want to know why following shows an InvalidCastException:
Object obj = 9;
long num = (long)obj; //InvalidCastException
After searching on net I find out Object considers 9 as Int so long doesn't exactly match Int.
My question is why Object considers 9 as Int but not short or long?
Because 9 is an Int32 literal. To specify an Int64 literal use
Object obj = 9L;
long num = (long)obj;
You can actually make this work if you explicitly say that it's a long. Pure numbers are read as integers, unless there are decimal points.
Object obj = 9L;
long num = (long)obj;
The following will also result in an invalid cast exception:
Object obj = 9L;
int num = (int)obj; //InvalidCastException
int is the default data type for non-decimal numeric literals, just as double is the default for decimal numeric literals. You can force numeric literals to other types with appropriate suffixes. You can use suffixes for int and double too but pretty much noone ever does.
Why this code won't compile without throwing an exception???
I am trying to convert float test to a character from ASCII table.
float test = 42.5F;
char convertFloatToChar = Convert.ToChar(test);
Console.WriteLine(convertFloatToChar);
All you need is a string:
float test = 42.5F;
String convertFloatToString = Convert.ToString(test);
Console.WriteLine(convertFloatToString);
If you check the overload for Convert.ToChar() then you will see that the exception is logical. You cannot have a float/double in Convert.ToChar() method.
ToChar(Double)
Calling this method always throws InvalidCastException.
You are probably looking for
float test = 42.5F;
String convertFloatToChar = Convert.ToString(test);
Console.WriteLine(convertFloatToChar);
I'm having trouble converting a string to a integer, my program is failing on this line
int newS = int.Parse(s);
With message:
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
The number I'm expecting back from my program is rather large. Below is the total program:
int math = (int)Math.Pow(2,1000);
string mathString = math.ToString();
List<string> list = new List<string>();
char[] ch = mathString.ToCharArray();
int result = 0;
foreach (char c in mathString)
{
string newC = c.ToString();
list.Add(newC);
//Console.WriteLine(newC);
}
foreach (string s in list)
{
int newS = int.Parse(s);
result += newS;
}
Console.Write(result);
Console.ReadLine();
You answered your own question. An int can only store numbers up to 2147483648 and an unsigned int up to 4294967296. try to use an ulong instead. I'm not sure about this but maybe a signed long may work.
EDIT: actually, in the msdn page it says this:
If the value represented by an integer literal exceeds the range of ulong, a compilation error will occur.
So probably you need a double.
Math.Pow(2, 1000) returns -2147483648.
So you'll end up with 11 items in your list, the first one being "-".
You can't convert a minus sign to int.
In all of the types of all languages are a limit on the numbers that you can save.
The int of c# is -2,147,483,648 to 2,147,483,647.
https://msdn.microsoft.com/en-us/library/5kzh1b5w.aspx
Math.Pow
returns a double, when you want to cast it to int your variable gets the value 0
Math.Pow(2,1000) returns: 1.07150860718627E+301.
If you use the double format you will try to cast the . and the E and the +, that are not a int then you can't use a int to save it.
that returns the FormatException that are answered here:
int.Parse, Input string was not in a correct format
Maybe you can try this:
int newS;
if (!int.TryParse(Textbox1.Text, out newS)) newS= 0;
result +=newS;
But will not use the 301 digits of the solution of 2^1000.
Is there any class in C# similar to Numberformat class in Java which, verify the string is a number.
NumberFormat numberFormat = NumberFormat.getInstance();
Number number = numberFormat.parse(string);
while trying for float with following parameter
float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out fValue),
the value=6666.77777 is rounded of to 6666.778.
can anyone help, i don't want my value to be rounded.
use int.TryParse it will return true if the number is int.
int.TryParse for integers.
float.TryParse for floats.
double.TryParse for doubles
Int64.TryParse for long.
e.g.
string str = "123";
int temp;
if (int.TryParse(str, out temp))
{
//its an int
}
else
{
// not an int
}
int a
bool isNumber = int.TryParse("500", out a);
replace int with whatever number you want to check for
I am working on a basic Battleship game to help my C# skills. Right now I am having a little trouble with enum. I have:
enum game : int
{
a=1,
b=2,
c=3,
}
I would like the player to pass the input "C" and some code return the integer 3. How would I set it up for it to take a string var (string pick;) and convert it to the correct int using this enum? The book I am reading on this is bit confusing
Just parse the string and cast to int.
var number = (int)((game) Enum.Parse(typeof(game), pick));
// convert string to enum, invalid cast will throw an exception
game myenum =(game) Enum.Parse(typeof(game), mystring );
// convert an enum to an int
int val = (int) myenum;
// convert an enum to an int
int n = (int) game.a;
just typecasting?
int a = (int) game.a
If you're not sure that the incoming string would contain a valid enum value, you can use Enum.TryParse() to try to do the parsing. If it's not valid, this will just return false, instead of throwing an exception.
jp
The answer is fine but the syntax is messy.
Much neater is something like this:
public DataSet GetBasketAudit(enmAuditPeriod auditPeriod)
{
int auditParam =Convert.ToInt32(auditPeriod) ;