Reputation: 957
I am trying to parse a very small number (ranges from 0 to 20). So, I know it is not the size issue. But my code still returns false all the time.
parseResult = int.TryParse(tempResult.ToString().Trim(), out Result);
Here tempResult is an object type as value can be an integer or a string. The value I am receiving is an integer (2, to be precise). And yet, parseResult is always false.
What am I missing here?
Edit: Apparently the value in the DB is saved as decimal and so actual value is 2M, instead of 2.0000. Now, how to fix this. I don't need the trailing zeros, just the value before decimal.
Edit: The value can be a string or a decimal. And I want to use just the decimal part. I can always cast to decimal directly, but that won't work if the value is a string.
Edit:
Full function:
object tempResult = bqObject.GetSingleValue(strQuery);
//get value from the system param table
if (tempResult == null)
{
tempResult = bqObject.GetSingleValue(strSysParamQuery);
}
//validate database values
if (tempResult == null)
{
throw new BaseException("DB100001");
}
else
{
parseResult = int.TryParse(tempResult.ToString().Trim(), out Result);
if (!parseResult)
{
throw new BaseException("DB100002");
}
}
First query reads a nvarchar column, while second one reads decimal column. So, I am trying to parse both to string, and then parsing to int. Problem is when the value is coming as decimal, tempResult.ToString().Trim()
line converts it to 2M
instead of 2.0000
. That's why the function fails.
Upvotes: 0
Views: 3048
Reputation: 1579
If you are passing in a decimal value, then an integer parse is going to return false. You have a couple of options. If you know it's always going to be a decimal format, change to using decimal.TryParse instead of int.TryParse Alternatively if you dont know if it'll be a whole number or decimal and want all results to be an integer, as you are already calling ToString, pass a string formatter "N0" in.
int.TryParse(tempResult.ToString("N0").Trim(), out Result);
N0 says Give me no decimal places. You can also use this N1, N2, etc...
This will always trim off the decimals (Effectively doing a Math.Floor(), which may not be what you want, in that case you should use the Math. methods to get the desired precision.
Upvotes: 1
Reputation: 1731
For converting something like 2.0000 or 2M you need to covert it to Decimal like decimal.TryParse(value)
and so you can convert decimal to int with Decimal.ToInt32(value)
for more information you can see this MSDN Page
Upvotes: 0
Reputation: 4658
Instead of parsing, you might want to try Convert.ToInt32. This takes care of most conversions - as long as you're getting base types.
You just have to be careful if you're getting null
values - in that case, Convert.ToInt32
returns 0
whereas int.TryParse
would throw an exception. If that's something you have to have to handle, you'll have to add an extra null-check before converting the value.
Upvotes: 1