My code is like this
string asd = "24000.0000";
int num2;
if (int.TryParse(asd, out num2))
{
// It was assigned.
}
Now code execution never enters to if case, that means try parse is not working. Can any one tell me whats wrong with the code.
Note:In first step The value 24000.0000 is purposefully assigned as string .
Use the second TryParse overload that allows you to specify NumberStyle parameters to allow for decimals.
int val =0;
var parsed = int.TryParse("24000.0000",
NumberStyles.Number,
CultureInfo.CurrentCulture.NumberFormat,
out val);
For an int, you cannot have decimal places.
EDIT:
string asd = "24000.000";
int dotPos = asd.LastIndexOf('.');
if (dotPos > -1) {
asd = asd.Substring(0, dotPos);
}
int num2;
if (int.TryParse(asd, out num2))
{
// It was assigned.
}
EDIT:
As pointed out by other answers, there are better ways to deal with the conversion.
See the remarks section of the MSDN documentation on this method:
http://msdn.microsoft.com/en-us/library/f02979c7.aspx
The string can only contain whitespace, a sign, and digits.
This should work for you:
string asd = "24000.0000";
int num2;
decimal tmpNum;
if (decimal.TryParse(asd, out tmpNum))
{
num2 = (int)tmpNum;
// It was assigned.
}
You've asked it to parse an int but given it a double or float. Since it can't parse the number it'll return false and set num2 to zero.
Related
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.
How can i make bitwise operations on strings at c#
example
string sr1="0101110";
string sr2="1101110";
sr1 & sr2="0101110";
or
sr1 | sr2="1101110";
How can i make such comparison ?
Notice string lengths are fixed 1440 characters
Here my dirty solution
private string compareBitWiseAnd(string sr1, string sr2)
{
char[] crArray1 = sr1.ToCharArray();
char[] crArray2 = sr2.ToCharArray();
StringBuilder srResult = new StringBuilder();
for (int i = 0; i < crArray1.Length; i++)
{
if (crArray1[i] == crArray2[i])
{
srResult.Append(crArray1[i]);
}
else
{
srResult.Append('0');
}
}
return srResult.ToString();
}
private string compareBitWiseOr(string sr1, string sr2)
{
char[] crArray1 = sr1.ToCharArray();
char[] crArray2 = sr2.ToCharArray();
StringBuilder srResult = new StringBuilder();
for (int i = 0; i < crArray1.Length; i++)
{
if (crArray1[i] == '1' || crArray2[i] == '1')
{
srResult.Append("1");
}
else
{
srResult.Append('0');
}
}
return srResult.ToString();
}
Convert to actual bits first, and then do the bitwise comparison.
int num1 = Convert.ToInt32(sr1, 2);
int num2 = Convert.ToInt32(sr2, 2);
int result = num1 & num2;
Use this if you want to get a binary string from the result.
BigInteger is the type you are looking for. It also have BitwiseOr.
If you really need to stick with strings it is not very hard to compute bitwise operations on character-by-character basis... but I'd avoid doing it if possible.
And here is a question on how to construct BigInteger from string of any base - BigInteger Parse Octal String?
var bitString = "10101";
BigInteger value = bitString.Aggregate(new BigInteger(), (b, c) => b * 2 + c - '0');
You have to convert the string to numbers first, you can use "Convert.ToInt32(String, Int32)", the second parameter lets you specify the base:
string sr1 = "0101110";
string sr2 = "1101110";
int one = Convert.ToInt32(sr1, 2);
int two = Convert.ToInt32(sr2, 2);
int result = one & two;
hope it helps.
You can't do bitwise operations on a string in the way you intend. There are interesting things you can do with bitwise operations on strings with other goals, like changing their case, but I think this is what you want:
// Convert the string to an integer
int foo = Convert.ToInt32(sr1, 2);
int bar = Convert.ToInt32(sr2, 2);
// Perform binary styff
int result = foo & bar;
// Convert back to a string, if you want
string resultStr = result.ToString();
I like Alexei's BigInteger solution, but it does require .NET 4.0 minimum. If for some reason you can't use that, then another option is to use the BitArray class, which has been available since .NET 1.1. Unfortunately, there is no method built-in to BitArray to parse a binary string, so you have to do that manually, similar to Alexei's solution.
Another option is a class I wrote called BoolArray which does a lot of the same things as BitArray, but does have a method to parse binary strings - use the static BoolArray.FromBinaryString method:
BoolArray bin = BoolArray.FromBinaryString("1001011000111010101"); // etc
Here is the BoolArray source code. Note, however, that it isn't quite complete, and isn't fully tested either, but I'm not immediately aware of any bugs.
EDIT: I noticed after pasting the original link that the code used a function provided in a different class of my "Utils" library, and wouldn't have compiled directly. I've updated the link to provide this class in the code as well... hopefully that was the only case, but if not let me know and I can fix.
int a = Convert.ToInt32(subjectsLabel1.Text);
int b = int.Parse(internetLabel1.Text);
int total = a+b;
label1.Text = total.ToString();
the error "Input string was not in a correct format." keeps poping out.
I tried to convert using the "int.parse" and the "convert.toint32" syntax but the same error keeps showing up.
*the values in the subjectsLabel1 and internetlabel1 would be coming from the database (which was done in visual studio) w/ datatype varchar(10).
There is nothing wrong with the way you are parsing those string values to integers. It's just that their value doesn't represent a valid integer so it cannot be parsed and an exception is thrown. You could use the int.TryParse method to handle gracefully this case:
int a;
int b;
if (!int.TryParse(subjectsLabel1.Text, out a))
{
MessageBox.Show("please enter a valid integer in subjectsLabel1");
}
else if (!int.TryParse(internetLabel1.Text, out b))
{
MessageBox.Show("please enter a valid integer in internetLabel1");
}
else
{
// the parsing went fine => we could safely use the a and b variables here
int total = a + b;
label1.Text = total.ToString();
}
If you're not sure the user is giving you a legal Int32 value to convert you can use:
int result;
if (!int.TryParse(subjectsLabel.Text, out result))
{
ShowAMessageToTheUser();
}
else
{
UseResult();
}
Using TryParse won't trow an exception when you try to parse a string. Instead it will return false and the out parameter is not valid to use.
You Cannot convert to Int32 if the string contains a decimal pointor its not a valid integer .Check
string test = "15.00"
int testasint = Convert.ToInt32(test); //THIS WILL FAIL!!!
Because Int32 does not support decimals. If you need to use decimals, use Float or Double.
So in this situation you can use
int.TryParse
also
Consider the need for a function in C# that will test whether a string is a numeric value.
The requirements:
must return a boolean.
function should be able to allow for whole numbers, decimals, and negatives.
assume no using Microsoft.VisualBasic to call into IsNumeric(). Here's a case of reinventing the wheel, but the exercise is good.
Current implementation:
//determine whether the input value is a number
public static bool IsNumeric(string someValue)
{
Regex isNumber = new Regex(#"^\d+$");
try
{
Match m = isNumber.Match(someValue);
return m.Success;
}
catch (FormatException)
{return false;}
}
Question: how can this be improved so that the regex would match negatives and decimals? Any radical improvements that you'd make?
Just off of the top of my head - why not just use double.TryParse ? I mean, unless you really want a regexp solution - which I'm not sure you really need in this case :)
Can you just use .TryParse?
int x;
double y;
string spork = "-3.14";
if (int.TryParse(spork, out x))
Console.WriteLine("Yay it's an int (boy)!");
if (double.TryParse(spork, out y))
Console.WriteLine("Yay it's an double (girl)!");
Regex isNumber = new Regex(#"^[-+]?(\d*\.)?\d+$");
Updated to allow either + or - in front of the number.
Edit: Your try block isn't doing anything as none of the methods within it actually throw a FormatException. The entire method could be written:
// Determine whether the input value is a number
public static bool IsNumeric(string someValue)
{
return new Regex(#"^[-+]?(\d*\.)?\d+$").IsMatch(someValue);
}
Well, for negatives you'd need to include an optional minus sign at the start:
^-?\d+$
For decimals you'd need to account for a decimal point:
^-?\d*\.?\d*$
And possible exponential notation:
^-?\d*\.?\d*(e\d+)?$
I can't say that I would use regular expressions to check if a string is a numeric value. Slow and heavy for such a simple process. I would simply run over the string one character at a time until I enter an invalid state:
public static bool IsNumeric(string value)
{
bool isNumber = true;
bool afterDecimal = false;
for (int i=0; i<value.Length; i++)
{
char c = value[i];
if (c == '-' && i == 0) continue;
if (Char.IsDigit(c))
{
continue;
}
if (c == '.' && !afterDecimal)
{
afterDecimal = true;
continue;
}
isNumber = false;
break;
}
return isNumber;
}
The above example is simple, and should get the job done for most numbers. It is not culturally sensitive, however, but it should be strait-forward enough to make it culturally sensitive.
Also, make sure the resulting code passes the Turkey Test:
http://www.moserware.com/2008/02/does-your-code-pass-turkey-test.html
Unless you really want to use regex, Noldorin posted a nice extension method in another Q&A.
Update
As Patrick rightly pointed out, the link points to an extension method that check whether the object is a numeric type or not, not whether it represents a numeric value. Then using double.TryParse as suggested by Saulius and yodaj007 is probably the best choice, handling all sorts of quirks with different decimal separators, thousand separators and so on. Just wrap it up in a nice extension method:
public static bool IsNumeric(this string value)
{
double temp;
return double.TryParse(value.ToString(), out temp);
}
...and fire away:
string someValue = "89.9";
if (someValue.IsNumeric()) // will be true in the US, but not in Sweden
{
// wow, it's a number!
]
I have a Double which could have a value from around 0.000001 to 1,000,000,000.000
I wish to format this number as a string but conditionally depending on its size. So if it's very small I want to format it with something like:
String.Format("{0:.000000000}", number);
if it's not that small, say 0.001 then I want to use something like
String.Format("{0:.00000}", number);
and if it's over, say 1,000 then format it as:
String.Format("{0:.0}", number);
Is there a clever way to construct this format string based on the size of the value I'm going to format?
Use Math.Log10 of the absolute value of the double to figure out how many 0's you need either left (if positive) or right (if negative) of the decimal place. Choose the format string based on this value. You'll need handle zero values separately.
string s;
double epislon = 0.0000001; // or however near zero you want to consider as zero
if (Math.Abs(value) < epislon) {
int digits = Math.Log10( Math.Abs( value ));
// if (digits >= 0) ++digits; // if you care about the exact number
if (digits < -5) {
s = string.Format( "{0:0.000000000}", value );
}
else if (digits < 0) {
s = string.Format( "{0:0.00000})", value );
}
else {
s = string.Format( "{0:#,###,###,##0.000}", value );
}
}
else {
s = "0";
}
Or construct it dynamically based on the number of digits.
Use the # character for optional positions in the string:
string.Format("{0:#,###,##0.000}", number);
I don't think you can control the number of decimal places like that as the precision of the double will likely mess things up.
To encapsulate the logic of deciding how many decimal places to output you could look at creating a custom formatter.
The first two String.Format in your question can be solved by automatically removing trailing zeros:
String.Format("{0:#,##0.########}", number);
And the last one you could solve by calling Math.Round(number,1) for values over 1000 and then use the same String.Format.
Something like:
String.Format("{0:#,##0.########}", number<1000 ? number : Math.Round(number,1));
Following up on OwenP's (and by "extension" tvanfosson):
If it's common enough, and you're on C# 3.0, I'd turn it into an extension method on the double:
class MyExtensions
{
public static string ToFormmatedString(this double d)
{
// Take d and implement tvanfosson's code
}
}
Now anywhere you have a double you can do:
double d = 1.005343;
string d_formatted = d.ToFormattedString();
If it were me, I'd write a custom wrapper class and put tvanfosson's code into its ToString method. That way you could still work with the double value, but you'd get the right string representation in just about all cases. It'd look something like this:
class FormattedDouble
{
public double Value { get; set; }
protected overrides void ToString()
{
// tvanfosson's code to produce the right string
}
}
Maybe it might be better to make it a struct, but I doubt it would make a big difference. You could use the class like this:
var myDouble = new FormattedDouble();
myDouble.Value = Math.Pi;
Console.WriteLine(myDouble);