I may have the following types:
Number with decimal : 100.90
Number (int32) : 32
String : ""
What I want is a function which tries to parse as a decimal and if it fails, then tries to parse as an int and if that fails then its a string.
Any sort of function in C# which has the following functionality is appreciated.
public static object cascadeParse(string obj)
{
decimal decRet;
if (!decimal.TryParse(obj, out decRet))
{
int intRet;
if (!int.TryParse(obj, out intRet))
{
return obj;
}
else
{
return intRet;
}
}
else
{
return decRet;
}
}
However this method will always return a decimal when passed something that can be parsed as an int as ints can always be parsed as decimal. You may want to re-order the TryParses to put the int one first.
TryParse() is your friend, however I don't understand what you want as all valid ints are also valid decimals.
Related
I'm trying to take objects out of an object list to an int list. If the object list's value contains a string than I want to convert it to an int. the error that I'm getting is "cannot convert from 'object' to 'System.ReadOnlySpan'. I've tried looking up examples and information about lists made of objects but couldn't find anything.
I'm also at a loss as to what to do with the 'else' part of the code.
public class ListFilterer
{
public static IEnumerable(int) GetIntegersFromList(List(object) listOfItems)
{
List<int> Integers = new List<int>();
foreach (var value in listOfItems)
{
int number = 0;
bool success = Int32.TryParse(value, out number);
if (success)
{
Integers.Add(number);
}
else
{
Integers.Add(number);
}
}
return Integers;
}
}
It'll probably work out if you TryParse value.ToString() instead, if you're looking for anything that might look like an int and can be converted to an int. If you only want things that actually are ints, something like if(value is int number) should work if your c# version is recent. If it's older you may have to if(value is int) and then cast the value inside the if
Your code can be simplified to:
foreach(...){
int.TryParse(value.ToString(), out var n);
integers.Add(n);
}
Or
foreach(...){
if(value is int)
integers.Add((int)value);
else
integers.Add(0);
}
You could simply use:
var ints = listOfItems
.Select(o => { int.TryParse(o.ToString(), out int num); return num;} )
.ToList();
This will work as you wish, as if conversion fails num is 0 by default.
If Try Parse fails number is automatically 0 so you can directly write this
Int32.TryParse(value, out int number)
Integers.Add(number);
Maybe you can find the better way
var intList = objs.ConvertAll(delegate (object obj) { return (int)obj; });
I have a web service function which has a decimal value i.e. BRGEW.
Client is supposed to send the decimal value but he's sending string from SOAP UI and it's failing in conversion.
I have done this to control it but doesn't work.
if (General.BRGEW == 0 || General.BRGEW.ToString() == "") {
General.BRGEW =0;
}
How can I control this?
I guess you need String.IsNullOrEmpty(String) method
Check here
You can try this if you want to check that user input is decimal or not
var check= double.IsNaN(variable); //It will return boolean value after that add your code logic
First you need to check if the value is null or empty, if it is not null or empty then convert it.
decimal number;
string value = "";
if(!String.IsNullOrEmpty(value))
{
if(Decimal.TryParse(value, out number))
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
{
Console.WriteLine("Unable to convert '{0}'.", value);
}
}
if (General.BRGEW == 0)
{
General.BRGEW = 0;
}
doesn't change things much :) If RRGEW is already 0, then setting it to zero will have little effect.
A. Make the client send the number
This would be the easiest solution.
B. Deal with it
If you cannot make the client send the number then the following could help:
Make General.BRGEW as string.
Create another property e.g. General.BRGEWAsInt
public class X {
public string BRGEW {get; set;}
public int BRGEWAsInt => Int32.TryParse(BRGEW, out var number)
? number
: 0;
}
You don't need to make a property, you could just parse when you need.
I'm trying to convert the string "127.0" to an integer.
I tried this function:
int getInt(string numStr)
{
int result;
int.TryParse(numStr, out result);
return result;
}
But when I call it as int x = getInt("127.0"); then int.TryParse() sets result to 0.
When I rewrite the function like this:
int getInt(string numStr)
{
result=Convert.ToInt32(numStr);
return result;
}
the same getInt() call throws this exception:
Input string was not in a correct format.
The issue here is that "127.0" is not an integer, it's a floating point number. You will need to parse it using one of the other floating point types (i.e. double, float, Decimal, etc.).
You may want to consider either stripping off any values after the decimal point and attempting to parse it, or parsing it as another type and casting it as an integer :
int result = (int)Convert.ToDouble("1.270");
You could also take advantage of the Math.Truncate() function which would give you the integer portion of your value :
int result = (int)Math.Truncate(Convert.ToDouble("127.0"));
First off, you need to check the return value of int.TryParse(). If it returns false, then the string could not be converted.
Had you done that, you would see it returned false because 127.0 does not describe an integer value (it describes a floating point value).
Note that decimal.TryParse() would succeed here. You need to figure out if you need an integer or floating point value, and reject data that is incorrect.
An int cannot contain a decimal point; that makes it either a double, a float, or a decimal. Try to pull the number minus anything from the decimal point over to the right, like this:
int getInt(string numStr)
{
int result;
string[] splitup;
string number;
if (numstr.Contains('.'))
{
splitup = numstr.Split('.');
number = splitup[0];
int.TryParse(number, out result);
}
else
{
int.TryParse(numstr, out result);
}
return result;
}
Rion Williams is absolutely correct, IMHO.
Along with the fact that what you are parsing is not an integer, I'd personally use the TryParse method. Many of the .NET types have it, and it's quite a bit "safer" (it won't throw exceptions) than just parsing a string.
Example:
string stringValue = "127.0";
int intValue;
if(Int32.TryParse(stringValue, out intValue))
{
// return value
}
// handle the failure
If you don't like that, I'd wrap it in a try-catch...
In C# Convert.ToInt32() and any method of Convert class can handle null values but all these method not handling "" as input. Throws an error "input string not in correct format"
Is there any way to handle/Convert "" to its specific value? like
Convert.ToInt32("") convert to 0
Convert.ToDecimal("") convert to 0.0
with out using if conditions
Thanks.
The POD classes in C# have a method just for this reason:
Int32.TryParse
You could even write an extension method to make this easier for you:
public static class Extensions {
public static decimal MyDecimalParse(this string val) {
decimal ret = decimal.Zero;
decimal.TryParse(val, out ret);
return ret;
}
} // eo class extension
Try int.TryParse
int i;
bool b = int.TryParse("", out i);
Console.WriteLine(b);
There isn't anything inherent in the frameworks that do this for you. It probably doesn't make sense for the entire community to understand "" as defaulting to 0 or 0.0 as you would want. I would recommend writing your own method that does what you specifically want.
Something to the effect of:
public class MyConvert
{
public static int ToInt32(string input)
{
return String.IsNullOrEmpty(input) ? 0 : Convert.ToInt32(input);
}
}
I realize you don't want to do the if check but you will have to check it one way or another (either by checking .IsNullOrEmpty or .TryParse), so abstracting it into your own convert method at least means you don't have to do it every time.
Using VS2010 Express, C# and it's WinForms Application.
Here I have three text boxes(aTextBox, bTextBox, cTextBox) from which Inputs are strings and then using int.Parse(aTextBox.Text) converted to integers.
Then a Button (calcBtn) method which is going to calculate charges and then to display results after some maths to particular TextBoxes on Result groupBox which again contains text boxes for results...
The problem is causing by the way I am parsing or the order in which it's executing. If any of the textbox is filled then result should display and not to get in the format exceptions. Here I am getting stuck because inside the calcBtn I am parsing all text boxes and if one of them is empty then exception occurs. Compiler is I guess trying to parse empty strings from the empty text boxes, and I don't want it to be.
Any suggestions if you got what I mean? :)
Here's what GUI looks like
You can use the extended method...
1) method
public static class TE
{
public static int StringToInt(this string x)
{
int result;
return int.TryParse(x, out result) ? result : 0;
}
}
2) use
System.Windows.Forms.TextBox t = new System.Windows.Forms.TextBox();
int x = t.Text.StringToInt();
The Int32.Parse method does not accept malformed strings, and this includes empty strings. I have two suggestions.
You could check if the string is empty/whitespace first, and return 0 or some other default value:
private static int ParseInteger(string str)
{
if (str == null || str.Trim() == "")
return 0;
// On .NET 4 you could use this instead. Prior .NET versions do not
// have the IsNullOrWhiteSpace method.
//
// if (String.IsNullOrWhiteSpace(str))
// return 0;
return Int32.Parse(str);
}
Or you could simply ignore all parsing errors, treating them as 0. This will treat things like "", "123abc", and "foobar" as zero.
private static int ParseInteger(string str)
{
int value;
if (Int32.TryParse(str, out value))
return value;
return 0;
}
Which approach you take depends on the specific needs of your application.
You can simply do:
private static int ParseInteger(string str)
{
int value;
Int32.TryParse(str, out value);
return value;
}
without any if, since TryParse set value to 0 if it fails