Code :
Decimal kilometro = Decimal.TryParse(myRow[0].ToString(), out decimal 0);
some arguments are not valid?
out decimal 0 is not a valid parameter - 0 is not a valid variable name.
decimal output;
kilometro = decimal.TryParse(myRow[0].ToString(), out output);
By the way, the return value will be a bool - from the name of the variable, your code should probably be:
if(decimal.TryParse(myRow[0].ToString(), out kilometro))
{
// success - can use kilometro
}
Since you want to return kilometro, you can do:
decimal kilometro = 0.0; // Not strictly required, as the default value is 0.0
decimal.TryParse(myRow[0].ToString(), out kilometro);
return kilometro;
Well, the decimal.TryParse returns a bool type - so you need to do something like:
Decimal kilometro;
// if .TryParse is successful - you'll have the value in "kilometro"
if (!Decimal.TryParse(myRow[0].ToString(), out kilometro)
{
// if .TryParse fails - set the value for "kilometro" to 0.0
kilometro = 0.0m;
}
The correct usage of the TryParse statement is given below.
You must declare the decimal first and then pass it into the TryParse method. If the TryParse succeeds, kilometro will be the new value, otherwise it will be zero. I believe that was your desired outcome.
decimal kilometro = 0;
if (Decimal.TryParse(myRow[0].ToString(), out kilometro))
{
//The row contained a decimal.
}
else {
//The row could not be parsed as a decimal.
}
Just as an additional answer, you can now declare out parameters inline.
if (decimal.TryParse(myRow[0].ToString(), out decimal outParamName))
{
// do stuff with decimal outParamName
}
Related
I wrote this function:
public static float parseFloat(string number)
{
float ishod = 0;
try
{
float.TryParse(number.Replace(".", ","), out ishod);
}
catch(Exception ex)
{
ishod = -1;
Console.WriteLine("parseFloat(): " + ex.Message);
}
return ishod;
}
because when entering float numbers like 4.5 in console application, it doesn't see the dot so it glues the two numbers. I get 45.
Though it will work, it is dubious when you pass 0 or -1 since you don't know if it produces error or a proper result.
I was wondering, does float type in C# has some number constant that represents an error state, so that I can return it and be sure something failed?
On the other hand what would be an error constant for integer in C#?
Or I should rethink my function and make it differently?
Well, floating point values have two kind of separators: decimal and thousand, e.g.
123,456,789.12
When parsing, thousand separators are ignored while decimal is turned into decimal point: "123,456,789.12" -> 123456789.12.
Please, note, that both separators are culture specific:
"123.456.789,12" // Russian Culture, "ru-RU" - comma is a decimal separator
"123,456,789.12" // English Culture "en-US" - dot is a decimal separator
In your case, you want to treat '.' as a decimal separtor, that's why let's parse it with Invariant Culture (your current culture treats '.' as a thousand separator and ignores it: "1.2" -> 12):
using System.Globalization;
...
public static float parseFloat(string number) {
// float.TryParse doesn't throw exceptions but returns true or false
if (float.TryParse(number,
NumberStyles.Any,
CultureInfo.InvariantCulture,
out float result))
return result;
else {
Console.WriteLine("Invalid floating point value.");
// Not A Number
return float.NaN;
}
}
Possible usage:
float value;
do {
Console.Write("Enter the value, please: ");
// Keep asking user
value = parseFloat(Console.ReadLine());
}
while (float.IsNaN(value)); // while the input provided is invalid
The TryParse method will not throw an exception in case of failure, it will simply return false. This makes your method redundant - you can simply do:
if(float.TryParse(someStringValue, out float ishod))
{
// success
}
else
{
Console.WriteLine("failed to parse {0} to float.", someStringValue);
}
If you really want to return a float whatever the conversion makes then you can return NaN when you are sure:
public static float parseFloat(string number)
{
float ishod = 0;
try
{
float.TryParse(number.Replace(".", ","), out ishod);
}
catch(Exception ex)
{
ishod = float.NaN;
Console.WriteLine("parseFloat(): " + ex.Message);
}
return ishod;
}
I am not inserting any value in VOUCHER_NO column and updating it.
But it is giving me error as
Input string was not in a correct format.Couldn't store <> in VOUCHER_NO Column. Expected type is Decimal.
Below is my code
drpayinfo[0]["VOUCHER_NO"] = e.Record["VOUCHER_NO"];
Update
I am using Oracle DB and its datatype is NUMBER (10)
Seems your e.Record["VOUCHER_NO"] have some unwanted content which is not convertible to decimal. Try this way checking before assignment or conversion
if(e.Record["VOUCHER_NO"] != "")
{
drpayinfo[0]["VOUCHER_NO"] = Convert.ToDecimal(e.Record["VOUCHER_NO"]);
}
But more safer way to detect and ignore bad content is
decimal result;
if (Decimal.TryParse(e.Record["VOUCHER_NO"], out result))
{
drpayinfo[0]["VOUCHER_NO"] = result;
}
else
{
// do stuff if failed to parese
}
Based on your comments on other answers, your value is an empty string. This cannot directly be converted to a decimal. You must decide some action to take instead.
They following code will try to convert it, and take an action if not. TryParse is your friend for conversions!
decimal num = 0;
if (!Decimal.TryParse(e.Record["VOUCHER_NO"], out num))
{
//Throw some error, maybe set num to some default and assign...
//The appropriate action in this situation depends on your needs.
}
else
{
//You can safely assign the value
drpayinfo[0]["VOUCHER_NO"] = num;
}
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...
I've got this code intended to convert null decimal vals to a "zero" value:
decimal paymentTot = TryConvertToDecimal(boxPaymentAmount.Text);
if ((null == paymentTot) || (paymentTot < 0))
{
paymentTot = 0M; // or simply 0?
}
private decimal TryConvertToDecimal(String incoming)
{
decimal result = 0.0M;
try
{
result = Convert.ToDecimal(incoming);
}
catch
{
; // nada
}
return result;
}
It compiles, but I get this warning: "The result of the expression is always 'false' since a value of type 'decimal' is never equal to 'null' of type 'decimal?'"
I don't grok just what it's trying to tell me. What sort of test do I need to appease the warning emitter and, more importantly, see to it that my code can equate to 'true' when that is the intent?
decimal is a value type and it can't be null.
If you want to have a nullable decimal then use Nullable<decimal> or decimal? which is a wrapper on decimal type, (it is still a value type though).
See: Nullable<T> Structure
You can also have your method for parsing as:
private Nullable<decimal> TryConvertToDecimal(String incoming)
{
Nullable<decimal> returnValue = null;
decimal result;
if (decimal.TryParse(incoming, out result))
{
returnValue = result;
}
return returnValue;
}
Also it is better to use decimal.TryParse if you are going to ignore the exception in parsing.
You don't Need your own Converter for this, use this instead:
decimal paymentTot;
if(!decimal.TryParse(boxPaymentAmount.Text, out paymentTot))
paymentTot = 0;
You possibly want to return a Nullable<decimal> (shorthand decimal?) from TryConvertToDecimal because decimal is a non-nullable value type.
private decimal? TryConvertToDecimal(String incoming)
{
try
{
return Convert.ToDecimal(incoming);
}
catch
{
return null;
}
}
var paymentTot = TryConvertToDecimal(boxPaymentAmount.Text);
if (!paymentTot.HasValue || paymentTot.Value < 0)
{
paymentTot = 0;
}
Note however that by convention TryXXX functions return bool and use an out argument to return the parsed value upon success. One of these built in to the Framework is decimal.TryParse which you might want to use instead:
decimal paymentTot;
if(!decimal.TryParse(boxPaymentAmount.Text, out paymentTot) || paymentTot < 0)
paymentTot = 0;
will default to 0 if the parsing fails or if the parsed value is < 0, as specified in your question. I would suggest this is most likely the solution you are looking for.
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.